0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

sqlserverでひとつのテーブル内でupsertを行う方法

Posted at

SQL分のsampleは以下の通り

upsert文
MERGE INTO test_table AS A
    USING (SELECT 10 AS no,'太郎さん' AS name, 30 AS age ) AS B
    ON
    (
       A.no = B.no
    )
    WHEN MATCHED THEN
        UPDATE SET
             name = B.name
            ,age = B.age
    WHEN NOT MATCHED THEN
        INSERT (no,name,age)
        VALUES
        (
             B.no
            ,B.name
            ,B.age
        )
;

Point:
'10'などがparameterとして渡される値になる
Aはtest_table全体を指す、
Bはparameterの値をtest_tableの特定のカラムに設定したものになっている
Aに対してBで設定した値で条件検索することにより、抽出したいレコードを取得できる

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?