存储过程:如果不存在记录,则运行不同的选择



在我的存储过程中,我有以下语句:

SELECT TOP 200 
    C.CustomerNumber,
    C.CustomerName,
    C.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 ('%' +  @searchString + '%') 
    OR C.CustomerNumber LIKE ('%' + CONVERT(VARCHAR(61), @searchString) + '%')))
ORDER BY
    C.CustomerName

我现在想检查一下,如果此选择未返回任何记录,请运行其他选择。

DECLARE @Temp Table
(
    CustomerNumber VarChar, //or whatever type these are
    CustomerName   VarChar,
    AccountManager VarChar,
    CustomerId     Int
)
INSERT INTO @Temp
SELECT TOP 200  
    C.CustomerNumber,
    C.CustomerName,
    C.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 ('%' +  @searchString + '%') 
    OR C.CustomerNumber LIKE ('%' + CONVERT(VARCHAR(61), @searchString) + '%')))
ORDER BY
    C.CustomerName
IF @@ROWCOUNT <> 0
    BEGIN
        SELECT * FROM @Temp
        RETURN
    END
SELECT * FROM OtherTable

我更喜欢这种方式

if exists (
    SELECT 1
    FROM 
        Customer C WITH(NOLOCK, index (UQ_Customer_CustomerNumber))
    LEFT JOIN 
        CustomerQuotingPreference cp WITH(NOLOCK) ON cp.CustomerId = C.CustomerId
    WHERE  
        (C.CustomerName LIKE ('%' +  @searchString + '%') 
        OR C.CustomerNumber LIKE ('%' + CONVERT(VARCHAR(61), @searchString) + '%')))
)
SELECT TOP 200  
    C.CustomerNumber,
    C.CustomerName,
    C.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 ('%' +  @searchString + '%') 
    OR C.CustomerNumber LIKE ('%' + CONVERT(VARCHAR(61), @searchString) + '%')))
ORDER BY
    C.CustomerName;
else
    SELECT * FROM OtherTable;

最新更新