2017-10-16 82 views
0
CASE 
    WHEN @vessel_certificate_id IS NULL 
     THEN SELECT 
       id, name as file_name, 
       SUM(DATALENGTH(data))/1048576.0 AS file_size, 
       dbo.fn_format_datetime(created_on) as file_date 
      FROM 
       vessel_cert_attachment 
      GROUP BY 
       id, name, type, created_by, created_on 
     ELSE 
      SELECT 
       id, name as file_name, 
       SUM(DATALENGTH(data))/1048576.0 AS file_size , 
       dbo.fn_format_datetime(created_on) as file_date 
      FROM 
       vessel_cert_attachment 
      WHERE 
       vessel_certificate_id = @vessel_certificate_id 
      GROUP BY 
       id, name, type, created_by, created_on 

此基礎上,如果參數是不是空的,我希望它沒有PARAM執行select語句,如果有PARAM傳球,我希望它執行與WHERE條件SELECT語句中的SQL。if else sql語句(選擇語句與參數和沒有參數)?

是否可以像那樣執行它?

+2

'CASE'在T-SQL是一種** **表達(如'一個+ B'),該**返回ONE,單個的原子值** - 你不能使用'CASE'來有條件地執行一個代碼塊或另一個代碼塊 - 爲此,你需要'IF .... ELSE ....' –

回答

0

使用OR條件Where子句

SELECT id, 
     NAME        AS file_name, 
     Sum(Datalength(data))/1048576.0 AS file_size, 
     dbo.Fn_format_datetime(created_on) AS file_date 
FROM vessel_cert_attachment 
WHERE (vessel_certificate_id = @vessel_certificate_id 
      OR @vessel_certificate_id IS NULL) 
GROUP BY id, 
      NAME, 
      type, 
      created_by, 
      created_on 
+0

Plus閱讀[T-SQL中的動態搜索條件](http: //www.sommarskog.se/dyn-search.html)Erland Sommarskog撰寫的文章,瞭解爲什麼您最好將'OPTION(RECOMPILE)'添加到這種查詢中。 –