我需要使用sql将状态名称列为核对表。即如果用户第一次登陆该页面,他应该看到所有状态,当他进入编辑模式时,他应该看到所有状态和所选状态必须被检查。如何使用单个存储过程实现此目的。我试过这个
create proc spGetList
AS
Begin
SELECT DISTINCT A.*
FROM State A
LEFT JOIN UserPreferedState B ON A.StateId = B.StateId
WHERE UserId = 3
End
但问题是我不知道如何在存储过程中添加新列(比如说IsSelected
)并将值设置为1如果选择了该状态并将值设置为0则该状态未被选中
示例:
表:UserPreferedState
Id UserId StateId
-------------------
1 1 1
2 1 2
3 2 1
4 2 2
5 3 1
表:State
Id StateName
--------------
1 ABC
2 DEF
3 GHI
我想要userid = 3
时的结果:
Id StateName IsSelected
--------------------------
1 ABC 1
2 DEF 0
3 GHI 0
我想要userid = 1
时的结果:
Id StateName IsSelected
-------------------------
1 ABC 1
2 DEF 1
3 GHI 0
答案 0 :(得分:1)
享受。这也是小提琴:http://sqlfiddle.com/#!3/217ce/2
CREATE TABLE state (
StateId INT,
StateName VARCHAR(100)
);
CREATE TABLE userPreferredState (
Id INT,
UserId INT,
StateId INT
);
INSERT INTO state (StateId, StateName)
VALUES (1, 'ABC'), (2, 'DEF'), (3, 'GHI');
INSERT INTO userPreferredState (Id, UserId, StateId)
VALUES (1, 1, 1), (2, 1, 2), (3, 2, 1), (4, 2, 2), (5, 3, 1);
CREATE PROCEDURE getStateListForUser @User int
AS
SELECT
s.StateId AS Id,
s.stateName,
CASE WHEN (ups.UserId = @User) THEN '1' ELSE '0' END AS IsSelected
FROM
State s
LEFT JOIN
UserPreferredState ups ON s.StateId = ups.StateId AND ups.UserId = @User
GO
要运行它,请致电:
EXEC getStateListForUser @User = 1
EXEC getStateListForUser @User = 3