Update query using Subquery in Sql Server

后端 未结 5 1339
走了就别回头了
走了就别回头了 2020-12-02 07:14

I have a simple table Structure like this:

Table tempData

╔══════════╦═══════╗
║   NAME   ║ MARKS ║
╠══════════╬═══         


        
5条回答
  •  失恋的感觉
    2020-12-02 07:39

    because you are just learning I suggest you practice converting a SELECT joins to UPDATE or DELETE joins. First I suggest you generate a SELECT statement joining these two tables:

    SELECT *
    FROM    tempDataView a
            INNER JOIN tempData b
                ON a.Name = b.Name
    

    Then note that we have two table aliases a and b. Using these aliases you can easily generate UPDATE statement to update either table a or b. For table a you have an answer provided by JW. If you want to update b, the statement will be:

    UPDATE  b
    SET     b.marks = a.marks
    FROM    tempDataView a
            INNER JOIN tempData b
                ON a.Name = b.Name
    

    Now, to convert the statement to a DELETE statement use the same approach. The statement below will delete from a only (leaving b intact) for those records that match by name:

    DELETE a
    FROM    tempDataView a
            INNER JOIN tempData b
                ON a.Name = b.Name
    

    You can use the SQL Fiddle created by JW as a playground

提交回复
热议问题