我有三列的表,第一列没有空值,但是其他两个都有空值我写了查询打击,所以我可以从表中获取数据,如果一个或两个或所有条件适合但是查询不是给我结果我想要它保持忽略具有空值的字段:
SELECT
ISNULL(IQCRM_NUM, 0) AS ASIQCRM_NUM,
ISNULL(Full_name, 0) AS ASFull_name,
ISNULL(Mother_Name, 0) AS Mother_Name,
ISNULL(Date_of_Birth, 0) AS Date_of_Birth,
ISNULL(Province_of_birth, 0) AS Province_of_birth,
ISNULL(Job, 0) AS Job
FROM [Criminal Main Table]
WHERE
(Full_name LIKE N'%' + @Full_name + N'%' OR @Full_name IS NULL) AND (Mother_Name LIKE N'%' + @Mother_Name + N'%' OR @Mother_Name IS NULL) AND (Date_of_Birth LIKE N'%' + @Date_of_Birth + N'%' OR @Date_of_Birth IS NULL)
如果任何条件适合,我希望查询从表中获取数据 这样的空值
如果我输入full_name(ali
),我想获得像
full_name |Mother_Name |Date_of_Birth
ali | huda |NULL
ali |NULL |1990
ali |NULL |NULL
ali |Noor |1988
答案 0 :(得分:0)
您需要正确构建LIKE
条件。变量应出现在LIKE
:
WHERE (Full_name LIKE '%' + @Full_name + '%' OR Full_name IS NULL) AND
(Mother_Name LIKE '%' + @Mother_Name + '%' OR Mother_Name IS NULL) AND
(Date_of_Birth LIKE '%' + @Date_of_Birth + '%' OR Date_of_Birth IS NULL)
答案 1 :(得分:0)
尝试这个,我猜你的问题是当你的一个参数有一个有效的值,但其他参数不为null并且值不在你的表中时,在这种情况下你的WHERE ... AND条件将永远不会为真< / p>
declare @table table
(
IQCRM_NUM int,
Full_name nvarchar(100),
Mother_Name nvarchar(100),
Date_of_Birth varchar(20),
Province_of_birth nvarchar(30),
Job varchar(50)
)
insert into @table values
(1, 'Ali', 'Huda', '2000-01-01', 'aaa', 'Job')
,(2, 'Ali', null, '2000-01-01', 'aaa', 'Job')
,(3, null, null, '2000-01-01', 'aaa', 'Job')
,(4, null, 'Huda', '2000-01-01', 'aaa', 'Job')
,(5, 'Ali', 'Huda', '2000-01-01', 'aaa', 'Job')
Declare @Full_name nvarchar(100)='Ali'
Declare @Mother_Name nvarchar(100)=null
Declare @Date_of_Birth nvarchar(20)=null --'2000-01-02'
SELECT
ISNULL(IQCRM_NUM, 0) AS ASIQCRM_NUM,
ISNULL(Full_name, '') AS ASFull_name,
ISNULL(Mother_Name, '') AS Mother_Name,
ISNULL(Date_of_Birth, '') AS Date_of_Birth,
ISNULL(Province_of_birth, '') AS Province_of_birth,
ISNULL(Job, '') AS Job
FROM @table
WHERE
(Full_name LIKE '%'+@Full_name + '%' OR @Full_name IS NULL)
AND (Mother_Name LIKE N'%' + @Mother_Name + N'%' OR @Mother_Name IS NULL)
AND (Date_of_Birth LIKE N'%' + @Date_of_Birth + N'%' OR @Date_of_Birth IS NULL)
option(recompile)