Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Returning counts into a value - which is faster?
Message
Information générale
Forum:
Microsoft SQL Server
Catégorie:
Stored procedures, Triggers, UDFs
Titre:
Returning counts into a value - which is faster?
Divers
Thread ID:
00513983
Message ID:
00513983
Vues:
50
I am doing some counts on a table (SQL 7) based on some criteria. The query is:

SELECT COUNT(*) AS NumRecs FROM [mytable] WHERE [some criteria]

I need to return the value lnCount as OUTPUT of a stored procedure. This can be accomplished by typing:

SELECT @NumRecs = COUNT(*) FROM [mytable] WHERE [some criteria]

and declare @NumRecs as an output parameter. However, [mytable] is a variable as well. I have managed to find two solutions, both of which seem to perform equally fast.

Solution 1
SET @lcParam = N'@NumRecs1 AS int OUTPUT'
SET @sqlcmd = 'SELECT @NumRecs1 = COUNT(*) FROM ' + @TableName + 'WHERE ...'
EXEC sp_executesql @sqlcmd, @lcParam, @NumRecs1 = @NumRecs OUTPUT


Solution 2
CREATE TABLE #tmp_count (cnt int)
SET @sqlcmd = 'INSERT #tmp_count SELECT COUNT(*)
FROM ' + @TableName + 'WHERE ...'
EXEC (@sqlcmd)
SELECT @NumRecs = cnt FROM #tmp_count


Is there a better way to do this? It seems to me that I am doing circles around the solution.

Thank you,
Aristotle
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform