【Sql】根据ID集合字符串,逗号拆分到临时表查询。

 1 ----1.获取到ID集合
 2 DECLARE @Key nvarchar(max)
 3 select @Key = CAST(Logger AS nvarchar(MAX)) from AIS20190728100136_LC..T_Jzc_ServicesLog where id=10763
 4 --print(@Key)
 5 ----2.把ID集合拆分到#Ids临时表
 6 CREATE TABLE #Ids(ID int)
 7 DECLARE @ID varchar(max)
 8 DECLARE @FinalID varchar(max)
 9 
10   WHILE(charindex(',',@Key) >0)
11   BEGIN
12   SET @ID = substring(@Key,0,charindex(',',@Key))
13  --print(@Id)
14  --set @FinalID = SUBSTRING(@ID,2,LEN(@Id)-2)
15   set @FinalID =REPLACE(@Id,'''','')
16   SET @Key = substring(@Key,charindex(',',@Key)+1,len(@Key))
17  --print(@Key)
18   INSERT INTO #Ids(ID) VALUES(@FinalID)
19   END
20    SET @Key =REPLACE(@Key,'''','')
21    INSERT INTO #Ids(ID) VALUES(@Key)
22 
23 
24 ----3.关联查询出中间表数据
25 select * from  ERP.dbo.WEB_Purchase t
26 where exists (select 1 from #Ids where id = t.id)
27 
28 ----4.手动释放临时表
29 DROP TABLE #Ids

@Key 的值为: '1','2','3','4'

posted @ 2019-07-29 11:09  嘿嘿嘿~  阅读(1160)  评论(0编辑  收藏  举报