在sql中的select查询中的case语句

时间:2013-09-16 18:28:03

标签: sql sql-server

我有一个存储过程将数据从一个表加载到另一个表。

我需要根据select语句的两个值设置目标表的列值,如下例所示。

insert into table table_name
( value1, value 2,value 3)

select (value 1,value2 ,
case value3 

when value1 = 'somevalue' &&* value2 = 'somevalue'

then 'x' 

else 'y'
End

from table_name.

任何人都可以帮我找出如何根据同一个选择查询中的前两个列值更新a列吗?

我尝试使用下面的示例示例来理解,但它无法解析。

INSERT INTO HumanResources.departmentcopy  
( DepartmentID,GroupName,Name,temp)

SELECT DepartmentID,GroupName,Name,
CASE temp
WHEN  DepartmentID = 1 && Name = 'Engineering and Research'
THEN 'sucessful'
ELSE 'unsucessful'
END
FROM HumanResources.department

帮助我!!

感谢, Venkat

3 个答案:

答案 0 :(得分:6)

你非常接近:

INSERT INTO HumanResources.departmentcopy(DepartmentID, GroupName, Name, temp)
SELECT  DepartmentID,
        GroupName,
        Name,
        CASE WHEN DepartmentID = 1 AND Name = 'Engineering and Research'
        THEN 'sucessful' ELSE 'unsucessful' END
FROM HumanResources.department

答案 1 :(得分:1)

&&在SQL中无效。使用AND附加条件。

INSERT INTO HumanResources.departmentcopy( DepartmentID,GroupName,Name,temp)
    SELECT  DepartmentID,
            GroupName,
            Name, 
            CASE
                WHEN DepartmentID = 1 AND Name = 'Engineering and Research' THEN 'sucessful' 
                ELSE 'unsucessful' 
                END 
            FROM HumanResources.department

答案 2 :(得分:0)

INSERT INTO HumanResources.department(DepartmentID, GroupName, Name, temp)

SELECT  DepartmentID,
        GroupName,
        Name,

CASE WHEN DepartmentID = 1 AND Name = 'Engineering and Research'

THEN 'sucessful' ELSE 'unsucessful' END

FROM HumanResources.department