开发者

SQL Server 2008 Merge Statement

开发者 https://www.devze.com 2023-03-19 11:11 出处:网络
I tried several times to execute the following MERGE statement, but I always got the same error message:

I tried several times to execute the following MERGE statement, but I always got the same error message:

Incorrect syntax near the keyword 'AS'.

Any idea why this error?

    CREATE TABLE StudentDetails
    (
        StudentID INTEGER PRIMARY KEY,
        StudentName VARCHAR(15)
    )
    GO

    INSERT INTO StudentDetails
    VALUES(1,'SMITH')
    INSERT INTO StudentDetails
    VALUES(2,'ALLEN')
    INSERT INTO StudentDetails
    VALUES(3,'JONES')
    INSERT INTO StudentDetails
    VALUES(4,'MARTIN')
    INSERT INTO StudentDetails
    VALUES(5,'JAMES')
    GO

    CREATE TABLE StudentTotalMarks
    (
        StudentID INTEGER REFERENCES StudentDetails,
        StudentMarks INTEGER
    )
    GO

    INSERT INTO StudentTotalMarks
    VALUES(1,230)
    INSERT INTO StudentTotalMarks
    VALUES(2,255)
    INSERT INTO StudentTotalMarks
    VALUES(3,200)
    GO

    MERGE StudentTotalMarks AS stm
    USING (SELECT StudentID,StudentName FROM StudentDetails) AS sd
    ON stm.StudentID = sd.StudentID
    WHEN MATCHED AND stm.StudentMarks > 250 THEN DELETE
    WHEN MATCHED THEN UPD开发者_JAVA百科ATE SET stm.StudentMarks = stm.StudentMarks + 25
    WHEN NOT MATCHED THEN
    INSERT(StudentID,StudentMarks)
    VALUES(sd.StudentID,25);


Your code works exactly as written for me.

Are you sure you are using SQL Server 2008?


You need SQL Server 2008 to use merge.

I have modified your code to use table variables instead just to prove that it works in SQL Server 2008.

You can test it here: https://data.stackexchange.com/stackoverflow/q/105423/test-merge

0

精彩评论

暂无评论...
验证码 换一张
取 消