SQL SERVER中Where子句中的动态条件 [英] Dynamic condtions in Where clause in SQL SERVER

查看:150
本文介绍了SQL SERVER中Where子句中的动态条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,







我必须写一个查询来生成报告,以便销售我公司的数据。该报告必须每天采取这样的方式,即它应包含从当月1日到前一天的数据。例如:2月24日生成的报告应包含2月1日至2月23日的数据。如果报告是在每月1日生成的,则应包含上个月的数据。



任何人都可以帮助动态编写SQL SERVER中的WHERE子句,它满足了这两个条件。



提前致谢,



Shanif

Hi All,



I have to write a query for generating report that gives sales data of my company. The report have to taken daily in such a way that it should contain data from 1st of the month till the previous day. For eg: report generated on Feb 24 should contain data from 1st Feb to 23 Feb. If the report is generated on 1st of every month, it should contain data for the previous month.

Can anyone help in writing dynamically the WHERE clause in SQL SERVER which satifies both the conditions.

Thanks in advance,

Shanif

推荐答案

您需要做的就是编写存储过程 [ ^ ](SP):

All you need to do is to write stored procedure[^] (SP):
CREATE PROCEDURE GetDataToReport

AS
BEGIN
    --declare varables:
    DECLARE @fdate DATETIME
    DECLARE @pdate DATETIME 
   
    --get current date
    SET @pdate = GETDATE()

    --get first day of month
    SET @fdate = DATEADD(month, DATEDIFF(month, 0, @pdate), 0)

    --get current date - 1
    SET @pdate = DATEADD(dd, -1, @pdate)

    --get data
    SELECT *
    FROM TableName
    WHERE DateField BETWEEN @fdate AND @pdate

END







如需了解更多信息,请参阅:

日期和时间数据类型和函数(Transact-SQL) [ ^ ]

从存储过程中返回数据 [ ^ ]


这篇关于SQL SERVER中Where子句中的动态条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆