2017-05-08 76 views
0

我有4個參數在sql查詢中動態傳遞,我想要在該條件中使用該參數過濾數據,並且至少有一個參數應該傳遞該值,可以爲null如何通過在Sql中使用傳遞參數來編寫Sql查詢

參數爲:@Orderstatusid@paymentStatusid@today@fromdate@todate

+0

你甚至試過在網上找這個嗎?這些是SQL Server相當基本的方面:https://www.mssqltips.com/sqlservertip/2981/using-parameters-for-sql-server-queries-and-stored-procedures/ – iamdave

+0

是的,我已經嘗試過我只有單個參數傳遞示例 –

+0

我一直試圖傳遞多個參數,這意味着即使一個參數傳遞了值或所有值,也應該讀取數據 –

回答

0

您需要設置每個輸入參數intially爲NULL,然後通過傳遞必要的參數覆蓋它。

ALTER PROC YOUR_PROCEDURE_NAME 
    (@Orderstatusid INT = NULL 
    ,@paymentStatusid INT = NULL 
    ,@today DATE = NULL 
    ,@fromdate DATE = NULL 
    ,@todate DATE = NULL 
    ) 
AS 
BEGIN 
     -- YOUR CODE HERE.... 
     -- YOUR WHERE CLAUSE SHOULD HAVE 
     Orderstatusid = @Orderstatusid OR 
     paymentStatusid = @paymentStatusid OR 
     today = @today OR 
     fromdate = @fromdate OR 
     todate = @todate 



END 
GO 

You can call your sp like below: 

EXEC YOUR_PROCEDURE_NAME @Orderstatusid = '101' 
OR 
EXEC YOUR_PROCEDURE_NAME @today = 'YOUR_DATE' 
... 
+0

@saikrishna - 你試過這個解決方案嗎? – balaji

0

您可以試試這個解決方案。

declare @whereCondition varchar(max) 
declare @sql varchar(max) 

if (@Orderstatusid is not null) 
set @whereCondition = 'Orderstatusid = ' + @Orderstatusid 

if (@paymentStatusid is not null) 
begin 
if(@whereCondition !='') 
begin 
    set @whereCondition = @whereCondition +' and paymentStatusid = ' + @paymentStatusid --use and/or as per your requirement 
end 
else 
begin 
    set @whereCondition = ' paymentStatusid = ' + @paymentStatusid 
end 
end 

-------write if condition for all cases 

set @sql= 'select * from TABLENAME where ' + @whereCondition 

exec @sql