亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

怎么查詢名稱對應的Id

怎么查詢名稱對應的Id

阿晨1998 2018-12-06 23:09:00
DECLARE @a VARCHAR(MAX)SET @a='管理員1,管理員2' 字符串格式就是這樣的,怎么用一個sql查詢出管理員1的Id,管理員2的Id 比如管理員1的Id是1 管理員2的Id是2 結果是這樣的 '1,2' 怎么才能用sql查詢出這個結果呢?
查看完整描述

4 回答

?
繁華開滿天機

TA貢獻1816條經驗 獲得超4個贊

雖然能這么干,但貌似不推薦這么干。

查看完整回答
反對 回復 2019-01-07
?
慕桂英546537

TA貢獻1848條經驗 獲得超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'


--用臨時表來存儲暫存數據
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);


--列出臨時表的數據,然后再用聯表查詢
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

查看完整回答
反對 回復 2019-01-07
?
慕標琳琳

TA貢獻1830條經驗 獲得超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)?

查看完整回答
反對 回復 2019-01-07
  • 4 回答
  • 0 關注
  • 854 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號