Sql Server存储过程按日期过滤?

时间:2017-03-03 09:22:29

标签: sql-server datetime

我是编写存储过程的新手,所以我有点卡住了 - 我想编写一个程序,我希望按日期过滤。我有一个保存日期时间的列,但我只想匹配日期时间值的日期部分。我该怎么办呢?这是我到目前为止所尝试的。 我有一个名为trxdate的列,其类型为datetime。

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)

3 个答案:

答案 0 :(得分:0)

尝试修改WHERE子句,如下所示:

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

并将参数作为

传递给过程
@TrxDate        date

proc调用将显示为

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

答案 1 :(得分:0)

如果存储过程参数和表数据库类型是datetime,则实际上不需要转换为varchar。如下

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

答案 2 :(得分:0)

您可以使用以下datetime操作从CAST字段中隔离日期/时间:

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

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