sql-server - 同一列的 Where 子句中的多个条件
问题描述
如何为以下条件编写 MS SQL 语句?
我有一个表单,允许用户在范围内输入日期 ( fromDate
& toDate
) 和 ID ( fromID
& toID
)。所有字段都可以为空或仅输入 from 或 to 字段或输入 from 和 to 字段。选择基于输入的值进行选择。以下是在 where 子句中检查输入值的条件。
no value entered => skip all conditions
value entered in fromDate only => Date = frDate
value entered in toDate only => Date <= toDate
value entered in both fromDate & toDate => Date between fromDate and toDate
Condition is applied to ID field as well.
任何建议都将受到高度赞赏。提前致谢。
解决方案
您可以使用动态查询来解决您的问题。你的问题并不完全清楚。在这里,我给你一个解决方案,这将帮助你解决你的问题。尝试这个:
1.在存储过程中创建动态查询
CREATE PROCEDURE sp_YourSPName
/* Input Parameters */
@FromDate DATETIME ,
@ToDate DATETIME
AS
SET NOCOUNT ON
/* Variable Declaration */
DECLARE @SQLQuery AS NVARCHAR(4000)
DECLARE @ParamDefinition AS NVARCHAR(2000)
/* Build the Transact-SQL String with the input parameters */
SET @SQLQuery = 'Select * From YourTableName where (1=1) '
/* check for the condition and build the WHERE clause accordingly */
IF (@FromDate IS NOT NULL)
AND (@ToDate IS NOT NULL)
SET @SQLQuery = @SQLQuery +
' And (YourDate BETWEEN @FromDate AND @ToDate)'
IF (@FromDate IS NULL)
AND (@ToDate IS NOT NULL)
SET @SQLQuery = @SQLQuery + ' And (YourDate <= @ToDate)'
IF (@FromDate IS NOT NULL)
AND (@ToDate IS NULL)
SET @SQLQuery = @SQLQuery + ' And (YourDate = @FromDate)'
/* Specify Parameter Format for all input parameters included
in the stmt */
SET @ParamDefinition = '@StartDate DateTime,
@EndDate DateTime'
/* Execute the Transact-SQL String with all parameter value's Using sp_executesql Command */
EXECUTE sp_Executesql @SQLQuery,
@ParamDefinition,
@FromDate,
@ToDate
IF @@ERROR <> 0
GOTO ErrorHandler
SET NOCOUNT OFF
RETURN(0)
ErrorHandler :
RETURN(@@ERROR)
GO
2.执行存储过程:
EXEC sp_YourSPName '01 Oct 2018', '01 Oct 2018'
推荐阅读
- ios - 使用 Cordova 的 Ionic 应用程序在 iOS 模拟器中工作但不在真实设备上
- android - 如何从 exoplayer 中删除搜索栏
- ios - CLFloor 返回级别 2146959360?
- database-design - BigQuery 表设计最佳实践:日期分区和分片的组合?
- pip - fbprophet 无限安装
- php - 在 WooCommerce 的购物车和结帐页面显示每件商品的总重量
- opencv - FAST 检测器最初是如何找到候选边缘的?任何边缘和特征检测器最初是如何找到候选者的?
- c# - 我需要使用什么 IP 来使用 C# 中的套接字通过 LAN 进行通信?
- installation - (Windows)安装程序如何包含文件?
- python - 如何在 Tkinter 中动态创建没有特定类实例化的小部件?