SQL Server将varchar字符串转换为int

时间:2012-07-26 11:21:53

标签: sql sql-server stored-procedures

大家好我有以下存储过程

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时,抛出错误转换失败。

任何人都可以给我一些指出来解决它

4 个答案:

答案 0 :(得分: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'

答案 1 :(得分:0)

而不是

WHERE     (QuestionId IN (@QuestionIdIn)) 

使用

WHERE charindex(','+cast(@QuestionId as varchar(100))+',',','+@QuestionID+',')>0

如果您担心性能,请使用拆分功能并加入主表

答案 2 :(得分: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')

答案 3 :(得分:0)

尝试改变条件:

WHERE     (QuestionId IN (@QuestionIdIn))

where (','+@QuestionIdIn+',' like '%,'+convert(varchar(50),QuestionId)+',%')

例如@ QuestionIdIn ='1,2,3,4,5,6'和QuestionId = 3表示:

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

如果3在此列表中,那么这是真的。