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

【SQL Server】変数を使ってwhile文みたいなループを書く

Posted at

変数をインクリメントしながら、ループでDB更新したいなあ
と思って調べたので残しておく

ループの書き方##

--変数を宣言
DECLARE @index INTEGER

--変数を初期化する
SET @index = 1

WHILE @index <= 10
BEGIN
    --ループしたいクエリを書く

	  SET @index = @index + 1
END

こんな感じで書くと変数indexが1~10まで増えて、10回ループできる。

update文のwhere条件をループで変える##

whereで指定する主キー(primary_key)の値をインクリメントさせてみる

--変数を宣言
DECLARE @id INTEGER

--変数を初期化する
SET @id = 100

WHILE @id <= 200
BEGIN
    update sales
	set 
	    column_name = 'テスト' 
	where id = @id 

	  SET @id = @id + 1
END

これでsalesテーブルのid列が100~200までのレコードを更新できます。

ただし、同じ値で更新するのにループさせるのは無駄の極みなのでご注意を(´·ω·`)

下のように書けば1回のupdateで更新できます

id BETWEEN 100 AND 200
--又は
id >= 100 AND id <= 200 

ループさせるのは各レコードの値も変えたい場合にしましょう

使い道##

私はテストデータの作成をする際に使用しました。

CONVERT関数で変数idをvarcharに変換して
各レコードupadeteしています。

--変数を宣言
DECLARE @id INTEGER

--変数を初期化する
SET @id = 31

WHILE @id <= 40
BEGIN
    update sales
	set 
	    column_name = ('テスト' + CONVERT(varchar, @id))
	  , status = '1'
	  , updt = getdate()
	where id = @id 

	  SET @id = @id + 1
END

参考##

こちらを参考にさせていただきました。
https://www.curict.com/item/bb/bb80194.html

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?