2012-07-26 59 views
0

大家好我有以下存儲過程SQL服務器轉換爲varchar字符串爲int

SELECT DISTINCT QuestionId, AnswerId, COUNT(AnswerId) AS Cntr, 
    (SELECT  COUNT(AnswerId) AS ttl 
    FROM   QUserAnswers 
    WHERE  (QuestionId = QUAM.QuestionId)) AS TtlCnt 
FROM   QUserAnswers AS QUAM 
WHERE  (QuestionId IN (@QuestionIdIn)) 
GROUP BY QuestionId, AnswerId 
ORDER BY QuestionId 

我在@QuestionIdI傳遞格式「1,2,3,4,5'然而,它的投擲VARCHAR值'1,2,3,4,5,6'轉換時轉換失敗的錯誤數據類型int

任何人都可以給我一些指點,如果你擔心服務表現理清

+2

您正在使用什麼版本的SQL Server? http://www.sommarskog.se/arrays-in-sql-2005.html – 2012-07-26 11:25:04

回答

1

正如他在其中提供的鏈接,建議由Tim Schelter: -

首先,你需要建立一個分析輸入

CREATE FUNCTION inputParser (@list nvarchar(MAX)) 
RETURNS @tbl TABLE (number int NOT NULL) AS 
BEGIN 
DECLARE @pos  int, 
     @nextpos int, 
     @valuelen int 

SELECT @pos = 0, @nextpos = 1 

WHILE @nextpos > 0 
BEGIN 
    SELECT @nextpos = charindex(',', @list, @pos + 1) 
    SELECT @valuelen = CASE WHEN @nextpos > 0 
          THEN @nextpos 
          ELSE len(@list) + 1 
        END - @pos - 1 
    INSERT @tbl (number) 
    VALUES (convert(int, substring(@list, @pos + 1, @valuelen))) 
    SELECT @pos = @nextpos 
END 
RETURN 
END 

然後使用該功能,在您的SP

功能
CREATE PROCEDURE usp_getQuestion 
@QuestionIdIn varchar(50) 
AS 
Begin 
Select Distinct QuestionId, AnswerId, COUNT(AnswerId) AS Cntr, 
    (SELECT  COUNT(AnswerId) AS ttl 
     FROM QUserAnswers 
     WHERE  QuestionId = QUAM.QuestionId) as TtlCnt 
from QUserAnswers AS QUAM 
inner join inputParser (@QuestionIdIn) i ON QuaM.QuestionId = i.number 
GROUP BY QuestionId, AnswerId 
ORDER BY QuestionId 
End 

EXEC usp_getQuestion '1, 2, 3, 4' 
+0

非常感謝 – 2012-07-26 12:35:27

0

而不是

WHERE  (QuestionId IN (@QuestionIdIn)) 

使用

WHERE charindex(','+cast(@QuestionId as varchar(100))+',',','[email protected]+',')>0 

,使用分割功能,並與主加盟表

+0

只是爲了解釋爲什麼它不起作用:in運算符需要一個表達式列表或一個表。你正在傳遞一個字符串。 – Andreas 2012-07-26 11:28:22

+0

你好,謝謝你,我試着charindex(','+ cast(@QuestionId +',',','+ @ QuestionID +',')> 0,它現在說'鑄造'附近有錯誤的語法,預計'AS'。順便說一句,是SqlServer 2005 – 2012-07-26 11:31:11

+0

@andrewslaughter更改'cast(@ QuestionId +'爲'cast(@QuestionId as nvarchar(20))+' – Curt 2012-07-26 11:38:55

0

試着在這裏應用這個邏輯。

Declare @str varchar(100)='''1'',''2'',''3'',''4'',''5''' 
select @str 
DECLARE @s int = 1 
select * from emp where CAST(@s as varchar) in ('1','2','3','4','5') 
0

試圖改變條件:

WHERE  (QuestionId IN (@QuestionIdIn)) 

where (','[email protected]+',' like '%,'+convert(varchar(50),QuestionId)+',%') 

例如,對於@ QuestionIdIn = '1,2,3,4,5,6' 和QuestionId = 3這意味着:

where (',1,2,3,4,5,6,' like '%,3,%') 

什麼是真,如果3在這個列表中。