2015-03-02 119 views
0

我想查詢查詢是否不返回任何結果,然後打印'找不到記錄',否則執行查詢。如何在SQL Server中的else語句中編寫SQL查詢

這裏是我的查詢,

select case when exists (
    SELECT CAST(dm.[ID] AS VARCHAR(100)) as ID, case when dm.[Que_Type] = 0 then 'Valid' else 'Invalid' end [Type], 
    dm.[Name_List], t.[Name], dm.[FromDate], dm.[ToDate] FROM tblDays dm(nolock) 
    inner join (select pr.ID, pr.name from tblProduct pr(nolock)) as t 
    on dm.TradeID = t.ID where 1=1 and dm.ToDate between GETDATE() and DATEADD(dd, 15, GETDATE())) 
then 'ok' 
else 'no records' 
end 

在此查詢,我想執行的,而不是打印「OK」查詢。我怎樣才能做到這一點?

回答

0

由於條件檢查只是爲了看看如果返回任何記錄,也沒有必要選擇這些欄你可以使用一個if聲明連同exists

,所以我們只是select 1。如果找到記錄,則if測試爲true,我們將運行sql語句。如果沒有找到記錄,我們將下降到else塊並print 'no records'

這可能會爲你工作:

IF(
    exists(
      select 1 
      FROM tblDays dm(nolock) 
      inner join (select pr.ID, pr.name from tblProduct pr(nolock)) as t 
       on dm.TradeID = t.ID 
      where 1=1 
      and dm.ToDate between GETDATE() and DATEADD(dd, 15, GETDATE()) 
     ) 
    ) 
BEGIN 
    SELECT CAST(dm.[ID] AS VARCHAR(100)) as ID 
      , case when dm.[Que_Type] = 0 then 'Valid' else 'Invalid' end [Type] 
      , dm.[Name_List] 
      , t.[Name] 
      , dm.[FromDate] 
      , dm.[ToDate] 
    FROM tblDays dm(nolock) 
     inner join (select pr.ID, pr.name from tblProduct pr(nolock)) as t 
      on dm.TradeID = t.ID 
    where 1=1 
    and dm.ToDate between GETDATE() and DATEADD(dd, 15, GETDATE()) 
END 
ELSE 
BEGIN 
    print 'no records' 
END 
0

你可以使用@@ROWCOUNT

根據BOL

返回受上一語句的行數。

SELECT 
    CAST(dm.[ID] AS VARCHAR(100)) AS ID, 
    CASE WHEN dm.[Que_Type] = 0 THEN 'Valid' ELSE 'Invalid' END AS [Type], 
    dm.[Name_List], 
    t.[Name], 
    dm.[FromDate], 
    dm.[ToDate] 
FROM tblDays dm(NOLOCK) 
INNER JOIN (
    SELECT 
     pr.ID, 
     pr.name 
    FROM tblProduct pr(NOLOCK) 
) AS t 
    ON dm.TradeID = t.ID 
WHERE 
    1 = 1 
    AND dm.ToDate BETWEEN GETDATE() AND DATEADD(dd, 15, GETDATE()) 

IF @@ROWCOUNT = 0 
    PRINT 'No records found.'