SQL Proc参数插入WHERE子句?

时间:2013-07-04 04:48:16

标签: sql

考虑下表:

myID    theirID    data
----    -------    ----
1       1          100
2       3          110
3       89         200
4       null       300
5       56         210

出于示例目的,这是非常简化的,但我有一个类似于此的proc作为报告的数据源:

SELECT myId, data
FROM myTable

然而,在proc运行之前,我想运行相同的proc来检查这样的空数据:

SELECT myId, data
FROM myTable
WHERE theirId IS NULL

现在,与我的例子不同,我的实际过程很复杂,我不想复制它。相反,我想要一个显示有问题数据的参数。所以我的问题是 - 我怎么能建立这样的东西:

create proc myProc (checkForBadData bit)
begin
    SELECT myId, data
    FROM myTable
    "but if checkForBadData = 1 then include 'WHERE theirId IS NULL'"
end

我可以在最后只插入一点动态SQL,还是必须污染整个事情?

谢谢!

1 个答案:

答案 0 :(得分:1)

将它添加到你的where子句中,你不需要任何动态的sql。

create proc myProc (checkForBadData bit)
begin
    SELECT myId, data
    FROM myTable
    WHERE checkForBadData = 0 or theirId IS NULL
end