views:

45

answers:

3

Hi,

Executing dynamic SQL as follows in Stored Procedure:

DECLARE @sqlCommand nvarchar(1000)
DECLARE @city varchar(75)
SET @city = 'London'
SET @sqlCommand = 'SELECT COUNT(*) FROM customers WHERE City = @city'
EXECUTE sp_executesql @sqlCommand, N'@city nvarchar(75)', @city = @city

How do I use the count(*) column value as return value in the SP?

+1  A: 

You've probably tried this, but are your specifications such that you can do this?

DECLARE @city varchar(75)
DECLARE @count INT
SET @city = 'London'
SELECT @count = COUNT(*) FROM customers WHERE City = @city
Brad
Or: SELECT @count = COUNT(*) FROM customers WHERE City = @city
Sage
Sage's comment is actually the preferred format.
OMG Ponies
@Sage, @OMG Ponies: good call. It's very different programming in a textbox on the web. :)
Brad
A: 
DECLARE @sqlCommand nvarchar(1000)
DECLARE @city varchar(75)
DECLARE @cnt int
SET @city = 'London'
SET @sqlCommand = 'SELECT @cnt=COUNT(*) FROM customers WHERE City = @city'
EXECUTE sp_executesql @sqlCommand, N'@city nvarchar(75)', @city = @city
RETURN @cnt
Parkyprg
I think your answer got cut off.
Sage
+3  A: 
DECLARE @sqlCommand nvarchar(1000)
DECLARE @city varchar(75)
declare @counts int
SET @city = 'New York'
SET @sqlCommand = 'SELECT @cnt=COUNT(*) FROM customers WHERE City = @city'
EXECUTE sp_executesql @sqlCommand, N'@city nvarchar(75),@cnt int OUTPUT', @city = @city, @cnt=@counts OUTPUT
select @counts as Counts
Sage
+1: You beat me to it, need to declare a variable, and mark it as an OUTPUT. [For more info, and a recommended read for SQL Server dynamic SQL, see The curse and blessings of dynamic SQL](http://www.sommarskog.se/dynamic_sql.html#sp_executesql)
OMG Ponies
Thank you. The OUTPUT keyword in N'@city nvarchar(75),@cnt int OUTPUT' was what I was missing.
Peter Lindholm