我的网站上有搜索过滤器。所以我需要获得年度产品的公司品牌名称
我想要更多的年份或者nulll
我使用split函数返回Table of years
declare @test nvarchar(50) = '1991,1997'
select BrandName from Item where DisplayPrice =1
and YearMan in (CASE WHEN @test is not null THEN (select * from split(@test,',')) ELSE YearMan END)
分割功能
ALTER FUNCTION [dbo].[Split](
@sInputList VARCHAR(8000) -- List of delimited items
, @sDelimiter VARCHAR(8000) = ',' -- delimiter that separates items
) RETURNS @List TABLE (item VARCHAR(8000))
BEGIN
DECLARE @sItem VARCHAR(8000)
WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
BEGIN
SELECT
@sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,@sInputList,0)-1))),
@sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,@sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))
IF LEN(@sItem) > 0
INSERT INTO @List SELECT @sItem
END
IF LEN(@sInputList) > 0
INSERT INTO @List SELECT @sInputList -- Put the last item in
RETURN
END
答案 0 :(得分:1)
您可以这样重写:
select BrandName
from Item
where DisplayPrice =1
and (@test IS NULL OR YearMan in (select item from split(@test,','))
答案 1 :(得分:0)
declare @test nvarchar(50) = '1991,1997'
select BrandName
from Item
where DisplayPrice =1
and @test is not null
and YearMan in (select * from dbo.split(@test,','))
union all
select BrandName
from Item
where DisplayPrice =1
and @test is null
-- or
declare @test nvarchar(50) = '1991,1997'
declare @array table (yyyy smallint primary key);
insert @array (yyyy)
select * from dbo.split(@test,',');
select BrandName
from Item
where DisplayPrice =1
and @test is not null
and YearMan in (select yyyy from @array)
union all
select BrandName
from Item
where DisplayPrice =1
and @test is null