T-SQL use different WHERE clause based on value of input parameter(T-SQL 根据输入参数的值使用不同的 WHERE 子句)
问题描述
我想根据输入参数的值更改查询的 WHERE 子句.我猜这是可能的,但似乎我以错误的方式接近它?
I would like to change the WHERE clause of a query based upon the value of an input parameter. I'm guessing this is possible, but it seems that I'm approaching it in the wrong way?
我的 SP 查询的简化版本:
A simplified version on my SP query:
CREATE PROCEDURE [dbo].[GetMailboxMessagesByStatus]
@UserId UNIQUEIDENTIFIER,
@MessageStatus INT
AS
BEGIN
SELECT *
FROM MailboxMessages m
WHERE
CASE @MessageStatus
WHEN 4 THEN m.SenderId = @UserId --Sent
ELSE m.RecipientId = @UserId --Inbox
END
END
GO
推荐答案
无需 case 或 iif 结构:
No need for case or iif constructs:
WHERE @MessageStatus = 4 AND m.SenderId = @UserId
OR @MessageStatus <> 4 AND m.RecipientId = @UserId
当被查询的表非常大时,请注意使用此构造的大表.使用 IF 语句(例如 Chester Lim)使用 2 个单独的查询可能是更好的解决方案.防止参数嗅探也可能是个好主意
Be aware on big tables using this construct when the table being queried is quite large. Using 2 seperate queries using a IF statement like Chester Lim suggested might be the better solution. Preventing parameter sniffing might also be a good idea
这篇关于T-SQL 根据输入参数的值使用不同的 WHERE 子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:T-SQL 根据输入参数的值使用不同的 WHERE 子句
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 更改自动增量起始编号? 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- SQL 临时表问题 2022-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
