如何在SQL中编写以下语句。
它给我带来了错误。
select * from a
where
a.Title = case when @Title is null or @Title = '' then a.Title else like %@Title% end
答案 0 :(得分:1)
这可以这样做:
select * from a
where ISNULL(@Title, '') = '' or a.Title like '%' + @Title + '%'
答案 1 :(得分:0)
这只会处理空值,但也许有人可以修改它来处理你的空char / varchar值......
SELECT *
FROM a
WHERE a.Title = COALESCE(@Title, a.Title)
答案 2 :(得分:0)
根据您对过滤条件的评论,这应该是您所追求的:
select * from a
where @Title is null or @Title = '' or a.Title like %@Title%
答案 3 :(得分:0)
语法错误是因为您使用的是%LIKE%,它不是有效的构造。要获得所需的结果,您可以根据条件运行两个不同的查询,如下所示:
if (@Title = null or @Title = '')
select * from a where a.Title = a.Title
else
select * from a where title like @Title
答案 4 :(得分:0)
你不能像这样混合运营商(=和之类)。看起来你正在尝试构建一个名为'like%Title%'的字符串,但你不能这样做。 Case只会返回一个值来比较某些东西(a.title)。正如其他几个人所说,你需要在两个测试之间使用OR。
答案 5 :(得分:0)
试试这个:
select
*
from @a a
where
a.Title = case when (@Title is null or @Title = '') then a.Title else @Title end
答案 6 :(得分:0)
只需将运算符更改为LIKE
,因为a.title = a.title
和a.title like a.title
在输出方面没有区别
select *
from a
where a.Title like case when @Title is null or @Title = '' then a.Title else %@Title% end
答案 7 :(得分:0)
您可以使用@Giorgi Nakeuri的答案,但需要澄清:
在您的查询中有一些错误:
%@Title%
之后的LIKE
LIKE
这是一个无效的表达式,您需要在LIKE '%' + @Title + '%'
CASE
之后使用字符文字。a.title
分支中使用相同类型的结果like %@Title%
然后SELECT *
FROM a
WHERE
1 = CASE
WHEN @Title IS NULL THEN 1
WHEN @Title = '' THEN 1
WHEN a.Title LIKE '%' + @Title + '%' THEN 1
ELSE 0
END
。所以你的正确查询应该是这样的:
SELECT *
FROM a
WHERE a.Title LIKE '%' + ISNULL(@Title, '') + '%'
但你可以这样简化:
`Private Sub Add_Click()`
`'ADD BUTTON `
`Dim CountRow As Long
If Me.txtName.Value = "" Then
MsgBox "Name.", vbExclamation, "Staff Information"
Exit Sub
End If`
`If Me.txtPhone.Value = "" Then
MsgBox "Phone.", vbExclamation, "Staff Information"
Exit Sub
End If`
`If Not IsNumeric(Me.txtPhone.Value) Then
MsgBox "Phone must contain only numbers.", vbExclamation, "Staff Information"
Me.txtPhone.SetFocus
Exit Sub
End If`
`If Me.txtEd.Value = "" Then
MsgBox "Education.", vbExclamation, "Staff Information"
Exit Sub
End If`
`CountRow = Worksheets("Sheet1").Range("A1").CurrentRegion.Rows.Count
CountRow = Worksheets("Sheet1").Range("A1").CurrentRegion.Rows.Count
With Worksheets("Sheet1").Range("A1")
.Offset(verRow, 0).Value = Me.txtname.Value
.Offset(verRow, 2).Value = Me.txtPhone.Value
.Offset(verRow, 4).Value = Me.txtEd.Value
End With`
`End Sub`