我在我的sql过程中编写两个查询,以根据我的asp.net应用程序中用户提供的参数检索数据。
IF @Action = 'ID'
SELECT Name,FirstName,LastName,Employee_ID,Location FROM Salary WHERE Employee_ID=@Employee_ID
ELSE IF @Action = 'LASTNAME'
SELECT Name,FirstName,LastName,Employee_ID,Location FROM Salary WHERE LastName like '%' + @LastName + '%'
现在我想要的是将查询组合成单个查询,这样无论ID是作为参数传递还是传递姓氏,我都必须能够获取数据。
非常感谢任何帮助。 提前致谢。
答案 0 :(得分:2)
如果所有参数可以一起使用:
SELECT Name,FirstName,LastName,Employee_ID,Location FROM Salary
WHERE Employee_ID=@Employee_ID or LastName like '%' + @LastName + '%';
一个参数 - 一个电话:
SELECT Name,FirstName,LastName,Employee_ID,Location FROM Salary
WHERE (@Employee_ID is not null and Employee_ID=@Employee_ID)
or (@Employee_ID is null and LastName like '%' + @LastName + '%')
答案 1 :(得分:1)
试试这个 -
SELECT
Name
, FirstName
, LastName
, Employee_ID
, Location
FROM dbo.Salary
WHERE Employee_ID = ISNULL(@Employee_ID, Employee_ID)
OR LastName LIKE '%' + @LastName + '%'
答案 2 :(得分:0)
SELECT Name,FirstName,LastName,Employee_ID,Location
FROM Salary
WHERE (@Action = 'ID' AND Employee_ID = @Employee_ID)
OR (@Action = 'LASTNAME' AND LastName like '%' + @LastName + '%')
答案 3 :(得分:0)
这解决了我的问题
SELECT Name, FirstName, LastName, Employee_ID, Location FROM Salary
WHERE Employee_ID = ISNULL(@Employee_ID, Employee_ID) and LastName LIKE '%' +
ISNULL(@LastName,LastName) + '%'