2

I am writing two queries in my sql procedure to retrieve data based on the parameter provided from the user in my asp.net application.

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 + '%'

Now what I want is to combine the query into single query so that irrespective of whether ID is passed as parameter or lastname is passed i must be able to get the data.

Any help would be greatly appreciated. Thanks in Advance.

4

4 回答 4

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 + '%')
于 2013-05-24T02:32:48.953 回答
1

试试这个——

SELECT 
      Name
    , FirstName
    , LastName
    , Employee_ID
    , Location 
FROM dbo.Salary 
WHERE Employee_ID = ISNULL(@Employee_ID, Employee_ID)
    OR LastName  LIKE '%' + @LastName + '%'
于 2013-05-24T05:10:52.243 回答
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 + '%')
于 2013-05-24T02:43:53.543 回答
0

这解决了我的问题

SELECT Name, FirstName, LastName, Employee_ID, Location FROM Salary
WHERE Employee_ID = ISNULL(@Employee_ID, Employee_ID) and LastName  LIKE '%' + 
ISNULL(@LastName,LastName) + '%'
于 2013-05-27T12:19:47.133 回答