您想要使用IN
的方式不正確,它不起作用。
選項:
- 發送CSV字符串到SP則將其分解,並創建一個臨時的數據集(例如表變量),您會那麼做
JOIN
- 動態SQL
實施例分解函數:
CREATE FUNCTION [dbo].[Split](
@String nvarchar (4000),
@Delimiter nvarchar (10)
)
RETURNS @ValueTable TABLE ([Value] nvarchar(4000), [ElementsCount] int)
BEGIN
DECLARE @nextString nvarchar(4000)
DECLARE @pos int
DECLARE @nextPos int
DECLARE @commaCheck nvarchar(1)
DECLARE @elementsCount int
SET @elementsCount = 0
--Initialize
SET @nextString = ''
SET @commaCheck = RIGHT(@string, 1)
--Check for trailing Comma, if not exists, INSERT
SET @string = @string + @delimiter
--Get position of first Comma
SET @pos = CHARINDEX(@delimiter, @string)
SET @nextPos = 1
--Loop while there is still a comma in the String of levels
WHILE (@pos <> 0)
BEGIN
SET @nextString = SUBSTRING(@string, 1, @pos - 1)
INSERT INTO @ValueTable ([Value]) VALUES (@nextString)
SET @string = SUBSTRING(@string, @pos +1, LEN(@string))
SET @nextPos = @pos
SET @pos = CHARINDEX(@delimiter, @string)
SET @elementsCount = @elementsCount + 1
END
UPDATE @ValueTable SET [ElementsCount] = @elementsCount
RETURN
END
然後喲u使用它像這樣:
SELECT
StudentName, Age
FROM
dbo.Students
JOIN [dbo].[Split](@city, ',') Cities ON City = Cities.Value
您需要使用某種分裂UDF功能的它拆分逗號分隔字符串,返回表變量,那麼你就可以加入或從這張表中選擇 – sll
你是什麼意思'這個查詢失敗'?它不返回結果,或者有錯誤? – Konerak