为了账号安全,请及时绑定邮箱和手机立即绑定

怎么查询名称对应的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 关注
  • 828 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信