我有一个在proc中运行的以下查询。函数MyFunction返回一个表,此查询将连接到该表。当提供@MyArg值时,此proc很有用。但是,我想知道是否有办法在数据库中的所有@MyArg值上运行它。我确信在循环中有一种方法可以做到,但我知道在db层通常要避免循环。
我真的只需要为了检查(并可能清理)一些不良数据而执行此操作。
SELECT ColumnA, ColumnB, ColumnC
FROM
(
SELECT
a.ColumnA,
a.ColumnB,
a.ColumnC,
ROW_NUMBER()
over(partition by a.ColumnD order by f.ColumnX) as RowNum
FROM dbo.MyTableA AS a
INNER JOIN dbo.MyFunction(@MyArg) f ON f.myID = a.myID
WHERE (a.myBit = 1 OR a.myID = @MyArg)
) AS x
WHERE x.rownum = 1;
答案 0 :(得分:1)
您可以使用交叉申请
with args as
(
select distinct myarg
from tbl
)
select f.*
from args
cross apply dbo.myfunction(myarg) f
答案 1 :(得分:0)
if @MyArg= 0
select @MyArg =null
SELECT ColumnA, ColumnB, ColumnC
FROM
(
SELECT
a.ColumnA,
a.ColumnB,
a.ColumnC,
ROW_NUMBER()
over(partition by a.ColumnD order by f.ColumnX) as RowNum
FROM dbo.MyTableA AS a
INNER JOIN dbo.MyFunction(@MyArg) f ON f.myID = a.myID
WHERE (a.myBit = 1 OR a.myID = @MyArg)
) AS x
WHERE x.rownum = 1;
在您的函数中添加
WHERE
(args.MyArg=COALESCE(@MyArg, args.MyArg) or (@MyArg is null))
这将搜索表中的所有MyArgs值