Reputation: 15
i want to do this:
DECLARE @str varchar(max)
DECLARE @cnt bigint
set @str= 'where column=value'
set @cnt= (select count(*) from user+@str)
but the where clause is not working. getting no error but it will just ignore the where condition.
Upvotes: 1
Views: 3729
Reputation: 2898
Check below code, in your case condition is dynamic so you need to dynamic sql.
DECLARE @sSQL nvarchar(500);
DECLARE @ParmDefinition nvarchar(500);
DECLARE @str nvarchar(500);
set @str= 'where column=value'
SELECT @sSQL = N'SELECT @retvalOUT = COUNT(*) FROM user '+ @str +' ' ;
SET @ParmDefinition = N'@retvalOUT int OUTPUT';
EXEC sp_executesql @sSQL, @ParmDefinition, @retvalOUT=@retval OUTPUT;
SELECT @retval;
Upvotes: 1
Reputation: 419
I previously suggested wrapping your last line in EXEC()
, but you can't do this and return results to a variable. To do that, use the following in place of your last line:
create table #temp (theCount int)
insert into #temp EXEC('select count(*) from Photos '+@str)
set @cnt= (select top 1 theCount from #temp)
drop table #temp
Upvotes: 2
Reputation: 169
use the execute sql syntax http://technet.microsoft.com/en-us/library/ms188001.aspx
Hope this will solve your problem
Upvotes: 0