我的存储过程中有以下内容:
DECLARE @CustomerNumber nvarchar(50)
SELECT TOP 200
C.CustomerNumber as SourceSystemId,
C.CustomerName,
AccountManager,
C.CustomerId
FROM
Customer C WITH(NOLOCK, index (UQ_Customer_CustomerNumber))
LEFT JOIN
CustomerQuotingPreference cp WITH(NOLOCK)ON cp.CustomerId = C.CustomerId
WHERE
(C.CustomerName LIKE ('%1725614%')
OR C.CustomerNumber LIKE ('%' + CONVERT(VARCHAR(61), '1725614' ) +'%'))
ORDER BY
C.CustomerName
IF @@ROWCOUNT = 0
BEGIN
SELECT DISTINCT
@CustomerNumber= C.CustomerNumber
FROM
[IFO].dbo.PricedealProposal PP
JOIN
IFO.dbo.OrderQuote OQ ON PP.OrderQuoteId = OQ.OrderQuoteId
JOIN
Customer C ON C.CustomerId = OQ.CompanyId
WHERE
PP.PriceDealProposalId = '1725614'
EXEC [dbo].[Customer_ListCustomerDetailsByCustomerNumber] @searchString = @CustomerNumber
END
当我运行这个时,我会得到两个选择的结果而不是最后一个:
如何根据满足的条件从一个选择中获得结果?
答案 0 :(得分:0)
有很多不同的方法可以做到这一点。想到的一种方法是,您可以将第一个选择的结果放入表变量或临时表中。然后基于行计数大于0来执行If / Else,或者如果存在,则从临时表类型的检查中选择1,并且基于if / else检查只有一个select执行,或者选择off临时表/变量或选择关闭选项B.
答案 1 :(得分:-1)
怎么样......
DECLARE @CustomerNumber nvarchar(50)
IF NOT EXISTS(
SELECT TOP 200 C.CustomerNumber as SourceSystemId
,C.CustomerName
,AccountManager
,C.CustomerId
FROM Customer C WITH(NOLOCK, index (UQ_Customer_CustomerNumber))
LEFT JOIN CustomerQuotingPreference cp WITH(NOLOCK)ON cp.CustomerId = C.CustomerId
WHERE (C.CustomerName like ('%1725614%')
OR C.CustomerNumber like ('%' + CONVERT(VARCHAR(61),'1725614' ) +'%'))
)
BEGIN
--NOTE TOP 1 HERE!
select TOP 1 @CustomerNumber= C.CustomerNumber
from [IFO].dbo.PricedealProposal PP
join IFO.dbo.OrderQuote OQ
on PP.OrderQuoteId = OQ.OrderQuoteId
join Customer C
on C.CustomerId= OQ.CompanyId
Where PP.PriceDealProposalId = '1725614'
EXEC [dbo].[Customer_ListCustomerDetailsByCustomerNumber] @searchString = @CustomerNumber
END
ELSE
BEGIN
SELECT TOP 200 C.CustomerNumber as SourceSystemId
,C.CustomerName
,AccountManager
,C.CustomerId
FROM Customer C WITH(NOLOCK, index (UQ_Customer_CustomerNumber))
LEFT JOIN CustomerQuotingPreference cp WITH(NOLOCK)ON cp.CustomerId = C.CustomerId
WHERE (C.CustomerName like ('%1725614%')
OR C.CustomerNumber like ('%' + CONVERT(VARCHAR(61),'1725614' ) +'%'))
END