3

I have a stored procedure to load the data from one table to another table.

i need to set the column value of the destination table based on the two values of the select statement, some thing like the below example.

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.

can any one help me to find out how to update the a column in based on the two previous column values in the same select query?

i have tried with the below sample example to understand but it was failed to parse.

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

Help me on this!!

thanks, Venkat

3 Answers 3

7

You were very close:

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
0
1

&& is not valid in SQL. Use AND to append a condition.

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
4
  • 1
    This is still wrong, you need to use CASE WHEN, not CASE temp WHEN
    – Lamak
    Sep 16, 2013 at 18:38
  • @Lamak Thanks. I inadvertently left that in after formatting it. Edited.
    – Khan
    Sep 16, 2013 at 19:13
  • @lamak: CASE temp WHEN is possible, but then you need to remove the column name from the when parts: sqlfiddle.com/#!6/a651f/1
    – user330315
    Sep 16, 2013 at 19:20
  • @a_horse_with_no_name I know that CASE <column> WHEN.. is possible, but for this question made no sense
    – Lamak
    Sep 16, 2013 at 19:24
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.