[英]Single SQL query with input tvp parameter when tvp doesn't contain any row
Anyone knows a kind of this trick 任何人都知道这种技巧
CREATE PROCEDURE [pr_GetFinDoc]
@id UNIQUEIDENTIFIER NULL
AS
BEGIN
SELECT f.*
FROM [dbo].[FinDocument] f --id column is primary key
WHERE @id is null or f.id = @id
END
So, the procedure
above returns either single FinDoc
or all FinDocs
. 因此,以上procedure
将返回单个FinDoc
或所有FinDocs
。 It depends on whether the id
was sent or not. 这取决于id
是否已发送。
Just a single query. 只是一个单一的查询。
So i need something like that but for tvp
parameter. 所以我需要类似的东西,但要使用tvp
参数。
It's my tvp
parameter - just array of uniqueidentifier
values 这是我的tvp
参数-仅是uniqueidentifier
值的数组
CREATE TYPE [dbo].[GuidList] AS TABLE(
[Id] [uniqueidentifier] NOT NULL,
PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (IGNORE_DUP_KEY = OFF)
)
And my stored procedure: 而我的存储过程:
CREATE PROCEDURE [pr_GetFinDoc]
@id_list [dbo].[GuidList] READONLY
AS
BEGIN
IF EXISTS (SELECT 1 FROM @id_list)
BEGIN
SELECT f.*
FROM
@id_list filter
INNER JOIN [dbo].[FinDocument] f
ON f.id = filter.Id
END
ELSE
BEGIN
SELECT f.*
FROM [dbo].[FinDocument] f
END
END
Is there a way to change the code of SP
with tvp input parameter
to single query ? 是否可以通过tvp input parameter
将SP
的代码更改为单个查询?
You can use IN
instead. 您可以改用IN
。 This gives you the flexibility to use more complex logic: 这使您可以灵活地使用更复杂的逻辑:
select f.*
from FinDocument f
where f.id in (select id from @id_list) or
not exists (select 1 from @id_list);
Note that these methods (and yours) are not necessarily efficient. 请注意,这些方法(以及您的方法)不一定有效。 The if
logic will probably compile using an index on id
. if
逻辑可能会使用id
上的索引进行编译。 Often if the queries are complex, it is better to either force a re-compile or use dynamic SQL (and force a re-compile) because of SQL Server compiles queries the first time the stored procedure is invoked. 通常,如果查询很复杂,最好是强制重新编译或使用动态SQL(并强制重新编译),因为SQL Server会在第一次调用存储过程时编译查询。 And the query plan may not be optimal for all parameter choices. 而且查询计划可能并非对所有参数选择都是最佳的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.