如果表值参数为null,我想获取列的所有值,否则只获取匹配的记录。我试过这个但是当子查询返回多个记录时它会出错:
ALTER PROCEDURE [dbo].[usp_MY_SP]
(
@TVP ABCTableType readonly,
)
AS
SELECT *
FROM TABLE t
WHERE
t.Id IN(
CASE WHEN (SELECT COUNT([Id]) FROM @TVP) > 0
THEN (SELECT [Id] FROM @TVP)
ELSE (t.Id)
END
)
答案 0 :(得分:2)
你可以这样做
ALTER PROCEDURE [dbo].[usp_MY_SP]
(
@TVP ABCTableType readonly
)
AS
SELECT * FROM t
WHERE
((SELECT COUNT([Id]) FROM @TVP) = 0)
OR
t.Id IN (SELECT [Id] FROM @TVP)