在 SQL 中创建带有嵌入引号的字符串
Create string with embedded quotes in SQL
我 运行 几个在 where 子句中使用字符值列表的查询,例如
select *
from table1
where col1 in ('a','b','c')
字符列表经常变化,所以我想将字符串存储在一个变量中并在所有查询中引用该变量,而不是维护字符串的多个副本。我尝试了以下但查询 returns 零行。
declare @str varchar(50)
select @str = '''a''' + ',' + '''b'''+ ',' + '''c'''
select *
from table1
where col1 in (@str)
@str 的值为 'a','b','c' 但由于某些原因,SQL 服务器无法识别它。如何构建字符串并将其存储在与 in 关键字一起使用的变量中?
可以创建带有嵌入引号的字符串。正如 Fredou 和 ChrisS 所提到的,@str 被视为单个字符串。如果将 @str 值与 select 语句的其余部分连接起来然后执行,您将获得所需的结果。 SQL Fiddle example.
declare @str varchar(50)
declare @sql varchar(MAX)
select @str = '''a''' + ',' + '''b'''+ ',' + '''c'''
Select @sql = 'SELECT * FROM table1 WHERE col1 IN (' + @str + ')'
Exec(@sql)
结果使用 @str = '''a''' + ',' + '''b'''+ ',' + '''c'''
结果使用 @str = '''a''' + ',' + '''b'''
SQL 中的 IN 构造作为集合查找,而不是字符串查找。您的单个字符串值“'a','b','c'”正是您说 where col1 in (@str)... 时要查找的内容,正如 Fredou 在评论中提到的。 =12=]
相反,您想通过使用 table 变量(或临时 table)传递一组值:
declare @tabIn table ( val varchar(10) )
insert @tabIn
(val) values
('a'), ('b'), ('c')
select *
from table1
where
col1 in (select val from @tabIn)
或者,或者直接连接:
declare @tabIn table ( val varchar(10) )
insert @tabIn
(val) values
('a'), ('b'), ('c')
select *
from table1 t1
join @tabIn t2 on
t1.col1 = t2.val
我 运行 几个在 where 子句中使用字符值列表的查询,例如
select *
from table1
where col1 in ('a','b','c')
字符列表经常变化,所以我想将字符串存储在一个变量中并在所有查询中引用该变量,而不是维护字符串的多个副本。我尝试了以下但查询 returns 零行。
declare @str varchar(50)
select @str = '''a''' + ',' + '''b'''+ ',' + '''c'''
select *
from table1
where col1 in (@str)
@str 的值为 'a','b','c' 但由于某些原因,SQL 服务器无法识别它。如何构建字符串并将其存储在与 in 关键字一起使用的变量中?
可以创建带有嵌入引号的字符串。正如 Fredou 和 ChrisS 所提到的,@str 被视为单个字符串。如果将 @str 值与 select 语句的其余部分连接起来然后执行,您将获得所需的结果。 SQL Fiddle example.
declare @str varchar(50)
declare @sql varchar(MAX)
select @str = '''a''' + ',' + '''b'''+ ',' + '''c'''
Select @sql = 'SELECT * FROM table1 WHERE col1 IN (' + @str + ')'
Exec(@sql)
结果使用 @str = '''a''' + ',' + '''b'''+ ',' + '''c'''
结果使用 @str = '''a''' + ',' + '''b'''
SQL 中的 IN 构造作为集合查找,而不是字符串查找。您的单个字符串值“'a','b','c'”正是您说 where col1 in (@str)... 时要查找的内容,正如 Fredou 在评论中提到的。 =12=]
相反,您想通过使用 table 变量(或临时 table)传递一组值:
declare @tabIn table ( val varchar(10) )
insert @tabIn
(val) values
('a'), ('b'), ('c')
select *
from table1
where
col1 in (select val from @tabIn)
或者,或者直接连接:
declare @tabIn table ( val varchar(10) )
insert @tabIn
(val) values
('a'), ('b'), ('c')
select *
from table1 t1
join @tabIn t2 on
t1.col1 = t2.val