SQL SERVER中Where子句中的动态条件

编程入门 行业动态 更新时间:2024-10-27 04:33:12
本文介绍了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子句中的动态条件

本文发布于:2023-10-25 14:31:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1527227.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:句中   条件   动态   SQL   SERVER

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!