2017-03-03 58 views
0

我是新來編寫存儲過程,所以我有點卡住了 - 我想編寫一個過程,我想按日期過濾。我有一個保存日期時間的列,但我只想匹配日期時間值中的日期部分。我該如何解決它?這是我到目前爲止所嘗試的。 我有一個名爲trxdate的類型爲datetime的列。Sql Server存儲過程按日期過濾?

USE [CAFFE] 
GO 
/****** Object: StoredProcedure [dbo].[p_paymentrecordsbydateandpaymentmode] Script Date: 3/3/2017 11:32:19 AM ******/ 
SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 
ALTER Procedure [dbo].[p_paymentrecordsbydateandpaymentmode] 
(
    @Country  VARCHAR(20), 
    @BankID   VARCHAR(20), 
    @ModeOfPayment VARCHAR(20), 
    @TrxDate  datetime 
) 
AS 
    SELECT  
     MobileNumber, 
     ModeOfPayment, 
     Branch, 
     ReceiptNo, 
     Amount, 
     TrxDate 

    FROM tb_TransactionRequests(NOLOCK) 
    WHERE @ModeOfPayment=ModeOfPayment and @TrxDate = CONVERT(VARCHAR(10),TrxDate,111) 

回答

0

嘗試修改WHERE子句這樣的:

WHERE @ModeOfPayment=ModeOfPayment and @TrxDate = cast(TrxDate as date) 

,並傳遞參數的程序,

@TrxDate  date 

PROC通話將如下

[dbo].[p_paymentrecordsbydateandpaymentmode] 1,1,'modeOfPayment','20170303' 
+0

@ DmitryCat-如何更改的程序,這樣我可以的日期內提取記錄範圍內並獲取該日期內的數據? –

+0

如果我真的瞭解你,你需要在\ @ date1和\ @ date2之間嘗試投射(TrxDate作爲日期) –

0

你實際上不需要如果存儲過程轉換爲varchar ure參數和表數據庫類型是datetime。正如下面

ALTER Procedure [dbo].[p_paymentrecordsbydateandpaymentmode] 
(
    @Country  VARCHAR(20), 
    @BankID   VARCHAR(20), 
    @ModeOfPayment VARCHAR(20), 
    @TrxDate  datetime 
) 
AS 
    SELECT  
     MobileNumber, 
     ModeOfPayment, 
     Branch, 
     ReceiptNo, 
     Amount, 
     TrxDate 

    FROM tb_TransactionRequests(NOLOCK) 
    WHERE @ModeOfPayment=ModeOfPayment and @TrxDate = TrxDate 
0

您可以通過以下CAST行動從datetime場隔離日期/時間:

-- Select date 
SELECT CAST(GETDATE() AS DATE); 

-- Select time 
SELECT CAST(GETDATE() AS TIME);