如何在SQL Server的case when子句中使用逗号分隔的数字

pbossiut  于 2023-01-25  发布在  SQL Server
关注(0)|答案(4)|浏览(195)

我试着用这样的代码

declare @Class varchar(20) 
set @Class = '4,6,8'

select 
    case when @Class in (1, 2) 
            then 1 
            else 0 
    end

Select 
    case when '4,6,8' in (1,2) 
       then 1 
       else 0 
    end

这将返回一个错误
将varchar值“4,6,8”转换为int数据类型时转换失败。
有没有办法在case when子句中使用这个拆分数字?
更新:实际上我在C#代码中使用了这段代码

private string Class()
    {
        if (this.RdFac.Checked)
        {
            return "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18";
        }
        else
        {
            if (this.CmbBrClass.SelectedValue.ToString() == "12")
            {
                return "12,16,18";
            }
        }
  }

private void ShwoResults_Click(object sender, EventArgs e)
    {
       dataTable = @"select 
        case when "+Class()+" in (1, 2) 
                then 1 
                else 0 
            end"
    }
vaqhlq81

vaqhlq811#

你可以试试这个...
在SQL Server 2012以下版本中:-

DECLARE @string NVARCHAR(100) = '12,14,15,1,2'
    ;WITH cte AS
    (
       SELECT 
          CAST('<XMLRoot><RowData>' + REPLACE(t.val,',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
          FROM (SELECT @string) AS t(val)
    ),
    ct as (
    SELECT 
        m.n.value('.[1]','varchar(8000)') as col
    FROM cte
    CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)
    ),
    ctfinal as (
          SELECT CASE WHEN CAST(col AS int) IN ( 1,2) THEN 1 ELSE 0 END AS RES FROM ct 
    )
    SELECT TOP 1 FROM ctfinal ORDER BY RES DESC

declare @Class varchar(20) 
    set @Class = '4,6,8,1'

    select 
        case when (@Class like '%1%' or @Class like '%2%')
                then 1 
                else 0 
        end

对于SQL Server 2012及更高版本:-

declare @Class varchar(20) 
    set @Class = '4,6,8,1'

    ; with cte as (
    select case when value in (1, 2) 
    then 1 else 0 end as res 
    from STRING_SPLIT ( @Class , ',' )
    ) 
    select top 1 res from cte order by res desc

为了比较你的int值,首先你需要把你的字符串分成rows中的各个int值。然后只有你可以在给定的条件下检查它们。
尽管in (1,2)在此查询中仍然是静态的。

bpsygsoo

bpsygsoo2#

错误您正在尝试比较int和varchar
这应该对你有用

declare @Class varchar(20) 
set @Class = '4,6,8,1'

select 
case
when value in (1, 2) 
then 1 
else 0 end as result 
from STRING_SPLIT ( @Class , ',' )
afdcj2ne

afdcj2ne3#

TRY:如果没有更多值可供比较,以下是即时解决方案
--如果有值

CASE WHEN ('1' IN (4,6,8) OR '2' IN (4,6,8)) 
THEN 1 
ELSE 0 END

--如果是变量

CASE WHEN ('1' IN (@Class) OR '2' IN (@Class)) 
THEN 1 
ELSE 0 
END
uplii1fm

uplii1fm4#

DECLARE @Class varchar(20)   
set @Class='4,6,8'  
DECLARE @intFlag INT  
DECLARE @temp INT  
SET @intFlag = 0  
WHILE (LEN(@Class)>0)  
BEGIN  
 if (CHARINDEX(',',@Class)=0)  
 begin  
 set @temp=@Class  
 set @Class=''  
 end  
 else 
 begin  
set @temp= SUBSTRING(@Class,1,CHARINDEX(',',@Class)-1)   
set @Class= SUBSTRING(@Class,CHARINDEX(',',@Class)+1,len(@Class)-CHARINDEX(',',@Class))
end   
set @intFlag= case when @temp in (1,2) then 1  else 0 end  
END  
select @intFlag

相关问题