如何检查逗号分隔的字符串值列表是否与整数匹配?

时间:2019-07-07 13:09:36

标签: sql-server tsql stored-procedures

下面,我添加了SQL查询。

我想检索符合条件的记录列表。我将整数值传递到@ClassID@SectionID参数中,问题是ce.Class_IDce.Section_ID是用逗号分隔的字符串值的列表。

SELECT ce.ID AS CircularEntryCount
FROM dbo.CircularEntry ce
WHERE ce.AcademicYearID = 1 
  AND (ce.Circular_Date = @CurrentDate OR CAST(ce.Created_Date AS date) = @CurrentDate)
  AND (ce.CircularApplicableForID = 1 OR ce.CircularApplicableForID = 3)
  AND (ce.Class_ID = @ClassID OR ce.Class_ID = '0') 
  AND (ce.Section_ID = @SectionID OR ce.Section_ID = '0')

PS:我使用了分割字符串函数将值分割为单独的列,并将其与参数进行比较,但显示出来了。

  

将数据类型nvarchar转换为bigint时出错

(     
      @List nvarchar(2000),
      @SplitOn nvarchar(1)
)
RETURNS @RtnValue table (
      Id int identity(1,1),
      Value nvarchar(100)
)
AS
BEGIN
      While (Charindex(@SplitOn,@List)>0)
      Begin 
            Insert Into @RtnValue (value)
            Select 
                  Value = ltrim(rtrim(Substring(@List,1,Charindex(@SplitOn,@List)-1))) 
            Set @List = Substring(@List,Charindex(@SplitOn,@List)+len(@SplitOn),len(@List))
      End 

      Insert Into @RtnValue (Value)
    Select Value = ltrim(rtrim(@List))

    Return
EN

1 个答案:

答案 0 :(得分:0)

正确的解决方案是解决问题-这意味着更改数据库的结构以根本不存储定界字符串,而是规范化数据并使用外键。
有关更多信息,请阅读Is storing a delimited list in a database column really that bad?,不仅要阅读Bill Karwin接受的答案,还要阅读其他答案。

如果无法更改数据库结构,则可以使用like的替代方法:

SELECT ce.ID AS CircularEntryCount
FROM dbo.CircularEntry ce
WHERE ce.AcademicYearID = 1 
  AND (ce.Circular_Date = @CurrentDate OR CAST(ce.Created_Date AS date) = @CurrentDate)
  AND (ce.CircularApplicableForID = 1 OR ce.CircularApplicableForID = 3)
  AND (','+ ce.Class_ID +',' LIKE '%,'+ CAST(@ClassID as varchar(20)) +'%,' OR ce.Class_ID = '0') 
  AND (','+ ce.Section_ID +',' LIKE '%,'+ CAST(@SectionID as varchar(20)) +'%,' OR ce.Section_ID = '0')

请注意强制转换为varchar(20)-bigint的min值包含一个负号和19位数字。如果@ClassID@SectionID的数据类型为int,则可以强制转换为varchar(11)