我有以下查询。当我运行它时,我会得到错误。最好的方法是什么?
declare @Slots varchar(50)
set @Slots = '1,2'
select * from Schedules where SlotID in (@Slots)
错误:
Msg 245,Level 16,State 1,Line 5转换时失败数据类型int.的varchar值"1,2">
您还可以使用STRING_SPLIT表值函数JOIN,该函数根据指定的分隔符将字符串拆分为多行子字符串。参见以下示例:
DECLARE @Schedules TABLE(SlotID int);
INSERT @Schedules VALUES (1),(2),(3),(4);
DECLARE @Slots varchar(50);
SET @Slots = '1,2';
SELECT *
FROM @Schedules S
JOIN STRING_SPLIT(@Slots, ',') ON S.SlotID=value
SQL Server不支持宏替换。但是,您可以使用string_split()
declare @Slots varchar(50)
set @Slots = '1,2'
Select *
From Schedules
Where SlotID in (select Value from string_split(@Slots,','))