【问题标题】:Stored procedure: if no record exists run different select存储过程:如果不存在记录,则运行不同的选择
【发布时间】:2018-03-06 20:27:12
【问题描述】:

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

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

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

【问题讨论】:

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


【解决方案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

【讨论】:

    【解决方案2】:

    我更喜欢这种方式

    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-13
      • 1970-01-01
      • 2015-06-16
      相关资源
      最近更新 更多