Home I cant get this conditional update or insert statement to work in SQL Server
Reply: 0

I cant get this conditional update or insert statement to work in SQL Server

user7854
1#
user7854 Published in September 19, 2018, 7:25 pm

This code is supposed to update a record if the name of the person in table 1 is the same as the name of the person in table 2 and if it is not then just insert the name and age of the person as a new record into table 1.

 SELECT
    CASE 
    WHEN
    [Name] = @Name 
    THEN
    UPDATE
    dbo.EmployeeInfo
    SET
    dbo.EmployeeInfo.Age = V.Age 
    FROM dbo.EmployeeInfo I
    INNER JOIN
    dbo.UpdateEmployeeInfo V
    ON
    V.[Name] = I.[Name]

    ELSE

    SELECT * INTO dbo.EmployeeInfo
    FROM dbo.UpdateEmployeeInfo
    WHERE [Name] = @Name

    END
    FROM dbo.EmployeeInfo

I have edited the code just to use IF conditions yet it still does not work

IF
dbo.EmployeeInfo.[Name] = @Name 
THEN
UPDATE
dbo.EmployeeInfo
SET
dbo.EmployeeInfo.Age = V.Age 
FROM dbo.EmployeeInfo I
INNER JOIN
dbo.UpdateEmployeeInfo V
ON
V.[Name] = I.[Name]

ELSE

SELECT * INTO dbo.EmployeeInfo
FROM dbo.UpdateEmployeeInfo
WHERE [Name] = @Name
share|improve this question
  • Use IF for conditional logic inside your queries. CASE is simply for modifying result sets inside a SELECT. – TZHX Nov 13 '17 at 14:02
  • @TZHX I cant get it to work even with IF logic – Bashir Nov 13 '17 at 14:03
  • 2
    You can't use CASE as a flow control element. Use IF instead. Also, You can't start with a SELECT statement and change it into an UPDATE statement before completing it. Seems to me like you are looking for Merge – Zohar Peled Nov 13 '17 at 14:04

1 Answer 1

active oldest votes
up vote 3 down vote accepted
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.30335 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO