对于不同的输入,是否可以编写不同的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,我想删除最后一行。
发布于 2014-07-04 03:21:36
您可以将此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;并对每个子句继续执行此操作。
发布于 2014-07-04 03:21:44
将最后一部分更改为:
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 + '%'))您可以在参数的开头添加%符号,但这将使任何索引无效。
发布于 2014-07-04 03:22:39
这是我在这些情况下通常使用的风格。
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 '%')https://stackoverflow.com/questions/24561540
复制相似问题