0

Null 許容パラメーターを持つストアド プロシージャがあり、以下は私のクエリです。

select * 
from table1
where table1.id = isnull(@id, table1.id)

現在、いくつかの特別な ID があり、それらを別の方法で扱います。以下のような別のテーブル table2 を追加しています

combid    id
1         abc01
1         abc02
1         abc03
2         hig01
2         hig02

次のケースを満たすようにクエリを変更する必要があります

  1. @idが null の場合、where 句は次のようになります。table1.id = table1.id
  2. @idnull でない場合、table2 に存在する場合は 2.1、where 句は 2.2 になります。
    それ 以外の場合、where 句は次のようになります。@idtable1.id in (select id from table2 where combid in (select combid from table2 where id=@id))
    table1.id = @id

次のクエリを試しましたが、うまくいきません。

select  * from table1
where (table1.id=@id and not exists(select * from table2 where id=@id)
or @id is null
or table1.id in (select id from table2 where combid in (select combid where id=@id)) and  exists(select * from table2 where id=@id))

ストアド プロシージャのクエリを変更するにはどうすればよいですか?

4

2 に答える 2

1
SELECT * FROM table1
WHERE
    @id IS NULL
    OR
    (
        @id IS NOT NULL
        AND
        (      
            (
                EXISTS (SELECT * FROM TABLE2 WHERE id = @id)
                AND
                table1.id IN (SELECT id FROM table2 WHERE combid in (SELECT combid FROM table2 WHERE id=@id))
            ) 
            OR
            (
                NOT EXISTS (SELECT * FROM TABLE2 WHERE id = @id)
                AND         
                table1.id = @id
            )
        )
    )
于 2013-03-28T16:52:26.720 に答える
0

SELECT ステートメントを 1 つだけ記述する代わりに、if...else... を使用できます。if else を使用すると読みやすくなります。


if(@id is null)
    select * from table1
else if exists (select 1 from table2 where id = @id)
    select * from table1 
    where table1.id in 
                  (select id from table2 where combid in 
                         (select combid from table2 where id=@id)
                  )
else 
   select * from table1 where table1.id=@id
于 2013-03-28T16:45:30.583 に答える