我正在尝试在sql语句中连接字符串。
我正在使用sql server,这就是它的外观;
declare
@SchoolID INT
,@Transaction nVarChar(35)
,@Reporting nVarChar(35)
,@SchoolOf nVarChar(35)
,@SchoolYear INT
,@Charter Varchar(25)
,@Value varchar(max)
SET @SchoolID = 105 -- HS - 65, MS - 66, ES - 67
SET @TransactionTypeCode = '' -- '', 'D', 'R'
SET @ReportingLEA = '1'
SET @SchoolOfAttendance = '1' -- HS - 1930056, MS - 6061238, ES - 6010862
SET @SchoolYear =295
SET @Charter = 'ALL'
SET @Value =
CASE @Charter
WHEN 'Los Angeles'
THEN 'Los Angeles'
WHEN'San Diego'
THEN 'San Diego'
WHEN 'Fresno'
THEN 'Fresno'
WHEN 'ALL'
THEN 'Los Angeles' + ',' +'San Diego'+ ','+'Fresno' --trying to concatenate data to show in the clause IN like charter IN ('Los Angeles','San Diego','Fresno')
END
print @Value
SET @SchoolID = 105 -- HS - 65, MS - 66, ES - 67
SET @TransactionTypeCode = '' -- '', 'D', 'R'
SET @ReportingLEA = '1'
SET @SchoolOfAttendance = '1' -- HS - 1930056, MS - 6061238, ES - 6010862
SET @SchoolYear =295
SET @Charter = 'ALL'
SET @Value =
CASE @Charter
WHEN 'Los Angeles'
THEN 'Los Angeles'
WHEN'San Diego'
THEN 'San Diego'
WHEN 'Fresno'
THEN 'Fresno'
WHEN 'ALL'
THEN 'Los Angeles' + ',' +'San Diego'+ ','+'Fresno' --trying to concatenate data to show in the clause IN like charter IN ('Los Angeles','San Diego','Fresno')
END
print @Value
我想要的是,如果用户选择“全部”
然后的价值
但是没有用。
我相信in子句不支持这种连接
如果运行此查询并将变量设置为“ ALL”,那么我将在打印结果中得到此信息:
@Value would be: 'Los Angeles' + ',' +'San Diego'+ ','+'Fresno'
inside the in clause:
AND gsrf.Charter in (@Value)
但是,如果我运行带有此结果的整个脚本(不进行IN分隔),则不会获得任何数据。
有什么建议吗?
答案 0 :(得分:0)
我不知道您在使用变量做什么,但是我认为您想要的逻辑更像是:
where (Charter = @Charter or @Charter = 'All')
答案 1 :(得分:0)
如果不执行动态语句,则不能在SQL的IN选择器中使用逗号分隔的字符串变量。
话虽如此,您可以通过将@Value类型更改为XML,然后查询XML来代替逗号分隔的字符串来实现目标。
因此,例如:
SET @Value = CASE @Charter
WHEN 'Los Angeles'
THEN '<cities><city>Los Angeles</city></cities>'
WHEN'San Diego'
THEN '<cities><city>San Diego</city></cities>'
WHEN 'Fresno'
THEN '<cities><city>Fresno</city></cities>'
WHEN 'ALL'
THEN '<cities><city>Los Angeles</city><city>San Diego</city><city>Fresno</city></cities>'
END
然后将@Value与IN选择器一起使用:
...AND gsrf.Charter IN (
SELECT x.f.value( '.', 'VARCHAR(35)' ) AS City FROM @Value.nodes( '//cities/city' ) x( f )
);
使用“ ALL”标志将从@Value返回以下内容:
+-------------+
| City |
+-------------+
| Los Angeles |
| San Diego |
| Fresno |
+-------------+