使用完整查询时的SQL Server查询案例

时间:2017-06-02 12:50:24

标签: sql sql-server case case-when

我正在尝试创建一个脚本。该脚本将声明一个带触发字的变量,然后我需要运行其中一个查询取决于触发字并返回所有结果,如:

DECLARE @name varchar(50)
set @name = 'value from the script'

select 
    case 
       when @name = 'orders' then (select * from orders)
       when @name = 'sales' then (select * from sales)
      ..etc
    end

但是这会导致错误,因为我正在尝试运行包含超过1行结果的完整查询。我被困在这里提前谢谢

3 个答案:

答案 0 :(得分:3)

声明变量并将查询分配给变量。

DECLARE @name varchar(50)
set @name = 'value from the script'
DECLARE @MyQuery NVARCHAR(MAX)

select 
    @MyQuery = CASE 
                    WHEN @name = 'orders' then 'select * from orders'
                    WHEN @name = 'sales' then 'select * from sales' 
                    ELSE 'SELECT 1' END

EXECUTE sp_executesql @MyQuery

答案 1 :(得分:2)

使用if

declare @name varchar(50);
set @name = 'value from the script';

if @name = 'orders' 
begin;
  select * from orders;
end;

if @name = 'sales' 
begin;
  select * from sales;
end;

答案 2 :(得分:0)

请尝试以下方法......

DECLARE @name VARCHAR(50)

SET @name = 'value from the script'
IF ( @name = 'orders' )
    ( SELECT * FROM orders )
ELSE IF ( @name = 'sales' )
    ( SELECT * FROM sales )