我想改进以下存储过程的代码。我想将它加入到单个select语句中。你能用更好的方式吗?
CREATE PROCEDURE [dbo].[pr_FinDocument_Filter]
@finDocIdForFilter [dbo].[GuidList] READONLY,
@filteredSid nvarchar(64),
@filteringOffsetInDay int
AS
BEGIN
IF (@filteredSid is null or @filteringOffsetInDay is null)
BEGIN
RAISERROR(N'arguments must have a value', 15, 1);
END
IF EXISTS (SELECT 1 FROM @finDocIdForFilter)
BEGIN
SELECT fin_doc_extra.docId
FROM
[CpsOther].[dbo].[FinDocumentExtra] AS fin_doc_extra
INNER JOIN @finDocIdForFilter AS fin_doc_for_filter
ON fin_doc_extra.docId = fin_doc_for_filter.Id
AND fin_doc_extra.sid = @filteredSid
WHERE
DATEDIFF(DAY, CONVERT(DATE, fin_doc_extra.value, 105), CONVERT(DATE, GETDATE(), 126)) = @filteringOffsetInDay
END
ELSE
BEGIN
SELECT fin_doc_extra.docId
FROM
[CpsOther].[dbo].[FinDocumentExtra] AS fin_doc_extra
WHERE
fin_doc_extra.sid = @filteredSid
AND DATEDIFF(DAY, CONVERT(DATE, fin_doc_extra.value, 105), CONVERT(DATE, GETDATE(), 126)) = @filteringOffsetInDay
END
END
答案 0 :(得分:2)
我认为这可能适合你。
SELECT fin_doc_extra.docID
FROM [CpsOther].[dbo].[FinDocumentExtra] AS fin_doc_extra
WHERE DATEDIFF(DAY, CONVERT(DATE, fin_doc_extra.value, 105),
CONVERT(DATE, GETDATE(), 126)) = @filteringOffsetInDay
AND fin_doc_extra.sid = @filteredSid
AND ( ( fin_doc_extra.docId IN ( SELECT fin_doc_for_filter.Id
FROM @finDocIdForFilter ) )
OR ( NOT EXISTS ( SELECT 1
FROM @finDocIdForFilter )
)
);
答案 1 :(得分:1)
我认为将2个选择合并为一个将不一定会改进您的代码。为了比较,这里有一个如何做到这一点的例子。我们有1个查询,但它更复杂,可以被认为不太可读。
以下查询基于您的第二个查询。我通过向WHERE语句添加一个附加条件来修改它。如果@finDocIdForFilter
为空或@finDocIdForFilter
包含匹配的行,则会满足此额外条件。
SELECT fin_doc_extra.docId
FROM
[CpsOther].[dbo].[FinDocumentExtra] AS fin_doc_extra
WHERE
fin_doc_extra.sid = @filteredSid AND
DATEDIFF(DAY, CONVERT(DATE, fin_doc_extra.value, 105), CONVERT(DATE, GETDATE(), 126)) = @filteringOffsetInDay
AND
(
NOT EXISTS(SELECT 1 FROM @finDocIdForFilter)
OR
EXISTS(
SELECT 1
FROM @finDocIdForFilter AS fin_doc_for_filter
ON fin_doc_extra.docId = fin_doc_for_filter.Ida.AssetCode)
)
答案 2 :(得分:0)
我对left outer join
SELECT TABLEA.Id
FROM
TABLEA
left join TVP
on TVP.Id = TABLEA.Id
WHERE
TABLEA.sid = @filteredSid
AND DATEDIFF(DAY, CONVERT(DATE, TABLEA.value, 105), CONVERT(DATE, GETDATE(), 126)) = @filteringOffsetInDay
AND
(
TVP.Id is not null
OR
NOT EXISTS (SELECT 1 FROM TVP)
)