开发者

SQL query in stored procedure; create a query with condition special parameter

开发者 https://www.devze.com 2023-03-04 01:15 出处:网络
Suppose I have tables Users, Roles and UserRoles (association). Then I want to create a s开发者_Go百科tored procedure with a parameter userid to return all the roles of that certain user. However if t

Suppose I have tables Users, Roles and UserRoles (association). Then I want to create a s开发者_Go百科tored procedure with a parameter userid to return all the roles of that certain user. However if the UserId is 1 (special Id), all roles should be returned.

My query on the SP should be like this without the special condition:

SELECT r.* 
FROM Roles 
INNER JOIN UserRoles ur ON r.Id = ur.RoleId 
WHERE ur.UserId = @userId;

How would I change this query to cater what I wanted? Or is this possible on a single query alone? I would not want to use IF..ELSE and use 2 queries.

Any comments are welcome.


Hi this will return all the user roles when @userId = 1

SELECT r.* 
FROM Roles 
INNER JOIN UserRoles ur
  ON r.Id = ur.RoleId
WHERE ur.UserId = @userId 
  OR @userId = 1
0

精彩评论

暂无评论...
验证码 换一张
取 消