如何在SQLServer存储过程中使用case语句

时间:2015-06-05 03:59:23

标签: sql-server sql-server-2008 tsql sql-server-2008-r2 sql-server-ce

我有一个存储过程,如:

Create  PROCEDURE GetValidationData(
@ContextKey INT  --Input parameter ,  Key to execute Statement 
)AS
BEGIN
if (@ContextKey = 1) 
begin 
 Select * from table A......
end
if (@ContextKey = 2) 
begin
 Some another select statement ......
end
.
.
.
.
.
.
.
.
.
like n
END

@ContextKey是执行正确的Select Statement

的参数

现在我想转换CASE WHEN THEN语句中的所有代码我该怎么做? 在@ContextKey

的基础上

1 个答案:

答案 0 :(得分:1)

你能试试吗

Create  PROCEDURE GetValidationData(
@ContextKey INT  --Input parameter ,  Key to execute Statement 
)AS
BEGIN
declare @sql nvarchar(max) 
select @sql = case @ContextKey 
                    when 1 then 'Select * from table A'
                    when 2 then 'Select another select statement'
                    when number then 'Select other '
                end
execute(@sql)

END
相关问题