Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
alanlambert
Starting Member
26 Posts |
Posted - 2004-09-27 : 08:02:38
|
I have a stored procedure which takes several parameters including one output parameter called @ProjectCount.The stored procedure returns several recordsets and must also set the value of the @ProjectCount parameter.All of the recordsets are created normally but the SQL needed to calculate the @ProjectCount parameter has to be generated dynamically.My problem comes when I try to assign a value to this parameter using dynamic SQL:DECLARE @Where varchar(1000)... -- Setting up @WhereEXEC('SELECT @ProjectCount = Count(*) FROM Basis WHERE ' + @Where)When this runs I get the message: Must declare the variable '@Count'.If I change the dynamic SQL to something static e.g.:SELECT @ProjectCount = Count(*) FROM Basis it works fine but, obviously, doesn't give me the result I need.Does anyone have any suggestions as to how to assign the value form the dynamic SQL to the output parameter as I'm tearing my hair out here!?Many thanks for your help.Alan |
|
|
slacker
Posting Yak Master
115 Posts |
Posted - 2004-09-27 : 08:15:35
|
quote: Originally posted by alanlambert I have a stored procedure which takes several parameters including one output parameter called @ProjectCount.The stored procedure returns several recordsets and must also set the value of the @ProjectCount parameter.All of the recordsets are created normally but the SQL needed to calculate the @ProjectCount parameter has to be generated dynamically.My problem comes when I try to assign a value to this parameter using dynamic SQL:DECLARE @Where varchar(1000)... -- Setting up @WhereEXEC('SELECT @ProjectCount = Count(*) FROM Basis WHERE ' + @Where)When this runs I get the message: Must declare the variable '@Count'.If I change the dynamic SQL to something static e.g.:SELECT @ProjectCount = Count(*) FROM Basis it works fine but, obviously, doesn't give me the result I need.
Try this.declare @sqlString nvarchar(1000)set @sqlString = N'SELECT @ProjectCount = Count(*) FROM Basis WHERE'+ @whereexec sp_executesql @sqlString,N'@ProjectCount int output',@ProjectCount=@ProjectCount output |
 |
|
|
alanlambert
Starting Member
26 Posts |
Posted - 2004-09-27 : 09:56:57
|
| That works perfectly.Many thanks for your help.Alan |
 |
|
|
|
|
|