sql query if parameter is null select all

sql query if parameter is null select all

Try this:

SELECT * 
FROM MY_TABLE 
WHERE @parameter IS NULL OR NAME = @parameter;

 

 

SQL select all if parameter is null else return specific item

回答1

Use case statement:

SELECT ProductID, ProductName,ProductDesc 
FROM product 
WHERE ProductID = CASE WHEN @productID IS NULL THEN ProductID ELSE @productID END

Or IIF() function if you’re using SQL Server 2012:

SELECT ProductID, ProductName,ProductDesc 
FROM product 
WHERE ProductID =IIF(@productID IS NULL, ProductID, @productID )

 

回答2

Why not just:

DECLARE @productID INT = NULL

SELECT ProductID, ProductName,ProductDesc 
FROM   product 
WHERE  ProductID = @productID
OR     @productID IS NULL;

Here a demo in SQLFiddle with NULL and a value for @productID

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(22)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2021-08-10 哈啰单车流量问题
2019-08-10 .net reflector
2017-08-10 数据库中的Convert
2017-08-10 xml Data Type Methods in sql server
2015-08-10 VS中常用的快捷键
2015-08-10 wcf中的File-less Activation
2015-08-10 什么是SysWow64
点击右上角即可分享
微信分享提示