我正在编写一个存储过程,该过程根据用户角色运行不同的选择,这只是展示我的意图的一个示例,因为我有很多角色要使用。
IF OBJECT_ID('dbo.spSelectArtigos') IS NOT NULL
DROP PROCEDURE spSelectArtigos
GO
CREATE PROCEDURE spSelectArtigos
@IdUser int,
@Acesso nvarchar(20)
AS
BEGIN
IF(@Acesso = 'User')
SELECT col1,col2 from table1 where IdUser = @IdUser
IF(@Acesso = 'Logistica')
SELECT col1,col2,col3 from table1 where IdUser = @IdUser
IF(@Acesso = 'Admin')
SELECT * From table1
END
有没有一种更有效的方法,可以使用某种逻辑用更少的代码来做到这一点?
答案 0 :(得分:1)
IDK为什么我添加了一个检查以确保用户实际存在,但这并不是一个坏主意
IF OBJECT_ID('dbo.spSelectArtigos') IS NOT NULL
DROP PROCEDURE spSelectArtigos
GO
CREATE PROCEDURE spSelectArtigos
@IdUser int,
@Acesso nvarchar(20)
AS
BEGIN
CASE
WHEN @Acesso ='User'
AND
EXISTS (SELECT * FROM table1 WHERE IdUser = @IdUser)
THEN
SELECT col1,col2 from table1 where IdUser = @IdUser
WHEN @Acesso ='Logistica' Then
AND
EXISTS (SELECT * FROM table1 WHERE IdUser = @IdUser)
THEN
SELECT col1,col2,col3 from table1 where IdUser = @IdUser
WHEN @Acesso ='Admin'
AND
EXISTS (SELECT * FROM table1 WHERE IdUser = @IdUser)
THEN
SELECT * From table1
END
END
答案 1 :(得分:1)
这是一种怪诞的方式,但很简洁。
IF OBJECT_ID('dbo.spSelectArtigos') IS NOT NULL
DROP PROCEDURE spSelectArtigos
GO
CREATE PROCEDURE spSelectArtigos
@IdUser int,
@Acesso nvarchar(20)
AS
BEGIN
DECLARE @Result TABLE(A INT,B INT,C INT,D INT)
INSERT @Result SELECT A,B,C,D FROM table1 WHERE idUser=@idUser
IF(@Acesso = 'User')
UPDATE @Result SET C=NULL, D=NULL
IF(@Acesso = 'Logistica')
UPDATE @Result SET D=NULL
SELECT * From @Result
END
另一种处理ID的方法
SELECT
A=CASE WHEN @Acesso >= 10 THEN A ELSE NULL END,
B=CASE WHEN @Acesso >= 20 THEN B ELSE NULL END,
C=CASE WHEN @Acesso >= 99 THEN C ELSE NULL END
FROM
table1
WHERE
idUser=@idUser