这不起作用,因为最终形成的查询是:
SELECT @STR = COALESCE(@str + ';','') + AnswerText
FROM SurveyQuestionAnswerTypes
WHERE AnswerType = (SELECT AnswerType
FROM SurveyQuestions
WHERE QuestionID = CAST(@QueId AS VARCHAR(4)))
AND AnswerValue IN ('2,3,5,7,8')
你想要这样的东西:
SELECT @STR = COALESCE(@str + ';','') + AnswerText
FROM SurveyQuestionAnswerTypes
WHERE AnswerType = (SELECT AnswerType
FROM SurveyQuestions
WHERE QuestionID = CAST(@QueId AS VARCHAR(4)))
AND AnswerValue IN (2,3,5,7,8)
我建议您制作一个 UDF String_To_Table,将字符串传递给该 UDF 并用于 IN 子句。
String_To_Table UDF:
CREATE FUNCTION [dbo].[String_To_Table]
(@string VARCHAR(4000),
@delimiter CHAR(1) = ';')
RETURNS @tbl TABLE (ord INT IDENTITY(1, 1) NOT NULL,
token VARCHAR(500)) AS
BEGIN
DECLARE @pos int,
@textpos int,
@chunklen smallint,
@tmpstr varchar(4000),
@leftover varchar(4000),
@tmpval varchar(4000)
SET @textpos = 1
SET @leftover = ''
WHILE @textpos <= datalength(@string)
BEGIN
SET @chunklen = 4000 - datalength(@leftover)
SET @tmpstr = @leftover + substring(@string, @textpos, @chunklen)
SET @textpos = @textpos + @chunklen
SET @pos = charindex(@delimiter, @tmpstr)
WHILE @pos > 0
BEGIN
SET @tmpval = ltrim(rtrim(left(@tmpstr, @pos - 1)))
INSERT @tbl (token) VALUES(@tmpval)
SET @tmpstr = substring(@tmpstr, @pos + 1, len(@tmpstr))
SET @pos = charindex(@delimiter, @tmpstr)
END
SET @leftover = @tmpstr
END
IF ltrim(rtrim(@leftover)) <> ''
INSERT @tbl(token) VALUES (ltrim(rtrim(@leftover)))
RETURN
END
然后你可以改变你的SP如下:
CREATE PROC RupeshTest(@QueID int, @Answer varchar(250)) as
BEGIN
DECLARE @STR varchar(4000)
SELECT @STR = COALESCE(@str + ';','') + AnswerText
FROM SurveyQuestionAnswerTypes
WHERE AnswerType = (SELECT AnswerType
FROM SurveyQuestions
WHERE QuestionID = CAST(@QueId AS VARCHAR(4)))
AND AnswerValue IN (SELECT Token FROM dbo.String_To_Table(@Answer,'^'))
END