2
4

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.

ストアドで引数が指定されたら絞込み、NULL なら無視

Last updated at Posted at 2013-03-22

たとえば 「@HogeId が指定されたら 1 件だけ処理、@HogeId が NULL の場合は絞り込まずに全件処理」 みたいなことがしたかったのだけど、

IF @HogeId IS NULL
BEGIN
  SELECT * FROM Hoge
END
ELSE
BEGIN
  SELECT * FROM Hoge WHERE HogeId = @HogeId
END

みたいなのしか思いつかなくてちょっと悩んだ。
(できれば条件がちょっと違うだけの SQL を何度も書きたくなかった)
ぐぐったら良さそうな方法を見かけたのでメモ。

ISNULL をかましてあげると良いらしい。

WHERE HogeId = ISNULL(@HogeId, HogeId)

CASE 文とか使う例もあったけど、これが一番見やすかった。

2
4
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
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?