是否可以编写SQL Transact查询,这对于不同的输入会有所不同?
我的意思是我有一个查询:
SELECT Entries.Date AS Date,
Users.UserName AS UserName,
Entries.Enter AS Enter,
Entries.Leave AS Leave
FROM Entries
INNER JOIN Users
ON (Entries.UserID = Users.Id)
WHERE UserName LIKE @UserName
如果没有提供@UserName,我想删除最后一行。
答案 0 :(得分:1)
您可以将此SQL编写为:
SELECT e.Date AS Date, u.UserName AS UserName, e.Enter AS Enter, e.Leave AS Leave
FROM Entries e INNER JOIN
Users u
ON e.UserID = u.Id
WHERE u.UserName LIKE @UserName or @UserName is NULL;
(别名只是使查询更容易编写和阅读。)
然而,有理由说这可能不是一个好主意。具有or
条件会使SQL Server更难使用索引。有了一个变量,它可能没问题。对于多个变量,这可能会对性能产生重大影响。
如果这是一个问题,那么在应用程序中将查询写为动态SQL。从where
子句开始,如:
declare @where varchar(8000) = '1=1'
然后构建它:
if @UserName is not NULL
begin
set @where = @where + ' and UserName = @UserName';
end;
并为每个条款继续。
答案 1 :(得分:1)
更改最后一部分,如:
SELECT Entries.Date AS Date,
Users.UserName AS UserName,
Entries.Enter AS Enter,
Entries.Leave AS Leave
FROM Entries
INNER JOIN Users
ON (Entries.UserID = Users.Id)
WHERE (@UserName IS NULL OR (UserName LIKE @UserName))
由于您在这里使用LIKE
,您是否会通过外卡?如果没有,你需要......
WHERE (@UserName IS NULL OR (UserName LIKE @UserName + '%'))
您可以在参数的开头添加%符号,但这会使任何索引无效。
答案 2 :(得分:0)
这是我在这些情况下通常使用的风格。
SELECT Entries.Date AS Date,
Users.UserName AS UserName,
Entries.Enter AS Enter,
Entries.Leave AS Leave
FROM Entries
INNER JOIN Users
ON (Entries.UserID = Users.Id)
WHERE (@UserName IS NOT NULL AND UserName LIKE '%' + @UserName + '%')
OR (@UserName IS NULL AND UserName LIKE '%')