带有in子句的case语句

时间:2013-09-08 01:49:16

标签: sql-server tsql

我有一个部分表,共有6个部分。我想根据部分插入不同的状态。所以基本上如果Sectionid = 1,2,5,6那么状态将插入1 else,如果该部分是3,4,则状态将插入0.我需要这个以插入所有6个部分的状态。我尝试使用案例陈述,但这不起作用。

表:Section

sectionkey int
sectionint int

sectionkey  sectionint
   1            1
   2            2
   3            3
   4            4

Status

statuskey int
statusint int
sectionint int

期望的输出:

    statuskey  statusint sectionint
      1            0          1
      2            0          2
      3            1          3
      4            1          4

我希望能够将第1节和第2节插入状态表并使状态为0,但也将第3节和第4节插入状态表,但在一个语句中使它们的状态等于1。

   DECLARE @SECTION int
   DECLARE @STATUS int
   --SET @SECTIONID = (SELECT SECTIONID FROM Section)

   SELECT CASE @STATUS 
   WHEN (SELECT SECTIONID FROM Section WHERE SECTIONID IN(1,2,5,6)) THEN '0' ELSE WHEN (SELECT SECTIONID FROM Section WHERE SECTIONID IN(3,4)) THEN '1' END END
   BEGIN
   INSERT INTO Checklist ("SECTIONID", "STATUS", "USERID")
   SELECT s.SECTIONID,@STATUS, @USER
   FROM SECTION as s 
   END

1 个答案:

答案 0 :(得分:1)

insert into Checklist("SECTIONID","STATUS","USERID")
    (select SECTIONID, (case when SECTIONID in(1,2,5,6) Then 0 Else 1 END), @USER
    from Section)