Getting result of dynamic SQL into a variable for sql-server
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
dynamic version
ALTER PROCEDURE [dbo].[ReseedTableIdentityCol](@p_table varchar(max))-- RETURNS int
AS
BEGIN
-- Declare the return variable here
DECLARE @sqlCommand nvarchar(1000)
DECLARE @maxVal INT
set @sqlCommand = 'SELECT @maxVal = ISNULL(max(ID),0)+1 from '+@p_table
EXECUTE sp_executesql @sqlCommand, N'@maxVal int OUTPUT',@maxVal=@maxVal OUTPUT
DBCC CHECKIDENT(@p_table, RESEED, @maxVal)
END
exec dbo.ReseedTableIdentityCol @p_table='Junk'
DECLARE @sqlCommand NVARCHAR(1000)
DECLARE @count INT
DECLARE @city VARCHAR(75)
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 = @count OUTPUT
SELECT @count