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

时间:2018-03-06 20:27:13

标签: sql sql-server-2008 stored-procedures

在我的存储过程中,我有以下声明:

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

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

我更喜欢这种方式

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;