4 回答

TA貢獻(xiàn)1848條經(jīng)驗 獲得超10個贊
一開始看到想用in的,好想拼接出來。最后試了好久不行。
下面是我測試可行的方法
create table test
( Id int primary key,
Name nvarchar(50)
)
insert into test values(1,'test1');
insert into test values(2,'test2');
insert into test values(3,'test3');
select * from test
declare @str nvarchar(max),@index int,@temp nvarchar(max)
set @str='test1,test2,test3'
--用臨時表來存儲暫存數(shù)據(jù)
drop table #temp_Table
create table #temp_Table
(
Name nvarchar(max)
)
--去除左右的空格
set @str=RTRIM(ltrim(@str))
set @index=CHARINDEX(',',@str);
while(@index>0)
begin
set @temp=SUBSTRING(@str,0,@index);
insert into #temp_Table values(@temp)
set @str=SUBSTRING(@str,@index+1,LEN(@str));
set @index=CHARINDEX(',',@str);
end
insert into #temp_Table values(@str);
--列出臨時表的數(shù)據(jù),然后再用聯(lián)表查詢
select * from #temp_Table
select Id from test
where name in (select Name from #temp_Table)
--輸出成這種格式'1,2,3',
declare @str3 nvarchar(max)
select @str3=ISNULL(@str3+',','')+
CAST(Id as nvarchar) from(select Id from test
where name in (select Name from #temp_Table)) AS T
select @str3

TA貢獻(xiàn)1830條經(jīng)驗 獲得超9個贊
拼接成字符串,然后in,最后exec(@sql)
DECLARE @a VARCHAR(MAX)
DECLARE @sql VARCHAR(MAX)
SET @a='管理員1,管理員2'
set @sql='select * from table where id in('+@a+')'
exec(@sql)?
- 4 回答
- 0 關(guān)注
- 851 瀏覽
添加回答
舉報