declare @pid int
declare @mid int
declare @tableName varchar(10)
declare @query nvarchar(1000)
declare @subquery nvarchar(300)
set @pid = 1
set @mid = 2
set @query = 'Select * from '+@tableName+' where'
if(@pid is not null)
begin
set @query = @query+' pid ='+@pid+' and'
end
if(@mid is not null)
begin
set @query = @query+' mid ='+@mid+' and'
end
如果@pid 和@mid 不为空,则添加到查询中。如果@pid 和@mid 为空,我想从查询中删除'where'。'and' 也一样,如果两者都被选中。
set @subquery = select right('''+@query+''',5)
if(@subquery = 'where')
begin
print @query
-- execute sp_executesql @query
end
但无法在 if 子句中比较这些。我需要执行@subquery。如果是,如何取该值?