13
15

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 5 years have passed since last update.

sql serverでカーソルを使う

Posted at

同じようなテーブルにデータを移行するときに
移行しようとしているテーブルにデータがある場合には更新したいので、
単純にinsert into マージするテーブル select マージしたいテーブル;みたいなのはできない。
なので、一行ずつ存在確認しながらやるしかない。そんなわけでカーソルを使ってみた。

テーブル定義
-- マージしたいテーブル
CREATE TABLE [dbo].[CardInfo](
    [CardID] [nchar](6) NULL,
    [CustomerID] [nchar](5) NULL
) ON [PRIMARY]

-- マージするテーブル
CREATE TABLE [dbo].[CardInfo2](
    [CardID] [nchar](6) NULL,
    [CustomerID] [nchar](5) NULL
) ON [PRIMARY]
merge.sql
-- 変数・カーソル定義

DECLARE cursorCardId  cursor FOR SELECT CardID, CustomerID FROM CardInfo;
DECLARE @cursorId nchar(6);
DECLARE @customerID nchar(5);


-- カーソルオープン
OPEN cursorCardId

-- データを格納
FETCH NEXT FROM cursorCardId
INTO @cursorId,@customerID


-- カーソルのデータが終わるまで繰り返す
 WHILE @@FETCH_STATUS = 0
 BEGIN

 -- 繰り返し処理
  IF EXISTS ( SELECT * FROM CardInfo2 WHERE [CardId]=@cursorId )
  BEGIN
    UPDATE CardInfo2
    SET    CustomerID=@customerID 
    WHERE  [CardId]=@cursorId;
  END
  ELSE
  BEGIN

    INSERT INTO CardInfo2
    ([CardId] ,[CustomerID]) VALUES
    (@cursorId, @customerID);
  END

  -- データを格納
  FETCH NEXT FROM cursorCardId
  INTO @cursorId,@customerID
END

-- カーソル終了処理
CLOSE cursorCardId
DEALLOCATE cursorCardId

13
15
2

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
13
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?