我在LIKE语句附近遇到sql inquery时遇到错误。我是否在CASE的WHEN子句中错误地格式化LIKE子句?这是代码。
SELECT
substring (Cases.FileNumber,4,6) AS [FileNumber]
,Charge.ChargeCode
,Cases.BookedLastName
,Cases.BookedFirstName
,Cases.ArrestDate
,Cases.BookedDOB
,Cases.BookedAge
,Charge.OffenseToDate
,Cases.BookedRace
,Cases.BookedSex
,Charge.OffenseStreetAddress1
,Charge.OffenseCity
,Charge.OffenseState
,Charge.OffenseZipCode
,Charge.ChargeDescription
,(SELECT CASE
WHEN charge1.ChargeDescription LIKE N'%heroin%' THEN 'Heroin'
ELSE 'Not Heroin'
END
FROM tblCsCharge AS charge1
INNER JOIN tblCsCases AS cases1
ON charge1.FileNumber = cases1.FileNumber
WHERE
charge1.BookedLastName = cases1.BookedLastName
AND charge1.BookedLastName = cases1.BookedLastName
AND charge1.BookedDOB = Cases.BookedDOB
AND cases2.ChargeCode IN (N'579.015-001Y201735')) AS HeroinYN
FROM
tblCsCases AS Cases
INNER JOIN tblCsCharge AS Charge
ON Cases.FileNumber = Charge.FileNumber
WHERE Cases.IssuedDate >= 01/01/2017
AND
Cases.IssuedDate <= @EndDate
AND
Charge.ChargeCode IN (N'579.015-001Y201735')
AND
Cases.BookedLastName NOT IN (N'Bogus')
ORDER By
Cases.BookedLastName
这是一个更大的查询中的一个子查询,专注于构建一个列,该列将根据我们数据库中的大文本字段输出Heroin或Not Heroin。
编辑:
尽管应该使代码编译的更改,但现在出现以下错误: 列名称无效&#39; BookedLastName&#39;。 列名称无效&#39; BookedLastName&#39;。 列名称无效&#39; BookedDOB&#39;。 多部分标识符&#34; cases2.ChargeCode&#34;无法受约束。
答案 0 :(得分:2)
您的代码中有两个错误,但都指出了这两个错误,但不是在同一个答案中。
,(SELECT CASE--(charge1.ChargeDescription)
WHEN charge1.ChargeDescription LIKE N'%heroin%' THEN 'Heroin'
ELSE 'Not Heroin'
END
FROM tblCsCharge AS charge1
INNER JOIN tblCsCases AS cases1
ON charge1.FileNumber = cases1.FileNumber
WHERE
charge1.BookedLastName = cases1.BookedLastName
AND charge1.BookedLastName = cases1.BookedLastName
AND charge1.BookedDOB = Cases.BookedDOB
AND cases2.ChargeCode IN (N'579.015-001Y201735')) AS HeroinYN
答案 1 :(得分:1)
这似乎是个问题..
CASE
由于这是子查询的一部分,因此您需要另一个括号
AND cases2.ChargeCode IN (N'579.015-001Y201735') AS HeroinYN
同时强>
使用等于运算符时,不能在AND cases2.ChargeCode IN (N'579.015-001Y201735')) AS HeroinYN
语句后面添加列名。
这是可以接受的
CASE
这不是
select
case columnName
when 'X' then 1
when 'Y' then 0
end
正确的脚本
select
case columnName
when = 'X' then 1
when columnName like '%Y%' then 0
end
答案 2 :(得分:0)
正确的语法是:
CASE
WHEN charge1.ChargeDescription LIKE N'%heroin%' THEN 'Heroin'
ELSE 'Not Heroin'
END
请勿在{1}}之后添加字段名称。