I have tried to write the store procedure with some condition check inside the Where
syntax.
But it only shows the status of the query instead of result.
Could any body help to resolve this issue.
Please find the query
declare @query varchar(200)
declare @option varchar(10) = 'A'
set @query ='select * from TableName'+
(case when @query = ''
then
'where ColumnName = 1 '
end)
execute sp_sqlexec @query
Your query should be
declare @query varchar(200)
declare @option varchar(10) ='A'
declare @search as int=1
select @query ='select * from TableName '+
case when @option ='A'
then
' where ColumnName = '+ cast(@search as varchar(200))
else ''
end
execute sp_sqlexec @query
What i can see for sure is lack of space before where condition.
declare @query varchar(200)
declare @option varchar(10) = 'A'
set @query ='select * from TableName'+
(case when @query = ''
then
' where ColumnName = 1 '
end)
You can try like this :
declare @query varchar(200)
declare @option varchar(10) = 'A'
set @query ='select * from TableName '
if @option ='A'
set @query = @query + ' where ColumnName = 1 '
--print @query
execute sp_sqlexec @query
declare @query nvarchar(max)
, @option varchar(10) = 'A';
set @query = N'select * from TableName '
+ CASE WHEN @option IS NOT NULL
THEN N' where ColumnName = 1 ' ELSE N'' END
execute sp_executesql @query;
Avoid using sp_sqlexec
it is very old and not supported anymore, use sp_executesql instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.