如果局部变量不为null,我想应用where子句。例如
declare @controlName nvarchar(250);
SELECT
*
FROM
(
SELECT TOP (100) PERCENT
dbo.Blah.PageName,
dbo.BlahBlah.ControlName,
dbo.BlahBlah.ControlText,
'en' AS FriedEgg
FROM
dbo.WebPageText INNER JOIN
dbo.Blah ON dbo.BlahBlah.WebPageID = dbo.Blah.WebPageID
if @controlName is not null
WHERE dbo.BlahBlah.ControlName = IN(@controlName, not null)
因此,如果控件名称变量不为null,则应用where子句
答案 0 :(得分:4)
最简单的答案......
SELECT TOP (100) PERCENT
dbo.Blah.PageName,
dbo.BlahBlah.ControlName,
dbo.BlahBlah.ControlText,
'en' AS FriedEgg
FROM
dbo.WebPageText
INNER JOIN
dbo.Blah
ON dbo.BlahBlah.WebPageID = dbo.Blah.WebPageID
WHERE
dbo.BlahBlah.ControlName = @controlName
OR @controlName IS NULL
答案 1 :(得分:2)
如果这是针对SQL Server的,您可以尝试使用ISNULL
函数:
DECLARE @controlName nvarchar(250);
SELECT
dbo.Blah.PageName,
dbo.BlahBlah.ControlName,
dbo.BlahBlah.ControlText,
'en' AS FriedEgg
FROM
dbo.WebPageText
INNER JOIN
dbo.Blah ON dbo.BlahBlah.WebPageID = dbo.Blah.WebPageID
WHERE
dbo.BlahBlah.ControlName = ISNULL(@controlName, dbo.BlahBlah.ControlName)
有了这个,如果@controlName
是NOT NULL
,那么您的WHERE
子句就是:
WHERE
dbo.BlahBlah.ControlName = @controlName
但是如果@controlName 是 NULL
,那么你得到
WHERE
dbo.BlahBlah.ControlName = dbo.BlahBlah.ControlName
并且总是如此,因此您不会限制结果集
答案 2 :(得分:0)
...
WHERE dbo.BlahBlah.ControlName = COALESCE(@controlName, dbo.BlahBlah.ControlNmae)
答案 3 :(得分:0)
尝试填充:
WHERE @controlName is null OR rest_of_the_condition
如果@controlName
为空,则无论WHERE
如何,它都将评估为真,rest_of_the_condition
子句为真。如果@controlName
不为空,rest_of_the_condition
子句中的WHERE
将生效。
答案 4 :(得分:0)
您是否尝试将IF测试放在WHERE子句中?
WHERE @controlName is not NULL AND dbo.BlahBlah.ControlName = IN(@controlName, not null)
答案 5 :(得分:0)
可以使用T-SQL:
declare @controlName nvarchar(250);
IF(@controlName IS NULL)
BEGIN
SELECT
*
FROM
(
SELECT TOP (100) PERCENT
dbo.Blah.PageName,
dbo.BlahBlah.ControlName,
dbo.BlahBlah.ControlText,
'en' AS FriedEgg
FROM
dbo.WebPageText INNER JOIN
dbo.Blah ON dbo.BlahBlah.WebPageID = dbo.Blah.WebPageID
END
ELSE
BEGIN
SELECT
*
FROM
(
SELECT TOP (100) PERCENT
dbo.Blah.PageName,
dbo.BlahBlah.ControlName,
dbo.BlahBlah.ControlText,
'en' AS FriedEgg
FROM
dbo.WebPageText INNER JOIN
dbo.Blah ON dbo.BlahBlah.WebPageID = dbo.Blah.WebPageID
WHERE dbo.BlahBlah.ControlName = @ControlName
END