2017-06-02 29 views
0

スクリプトを作成しようとしています。このスクリプトは、トリガ・ワードを使用して変数を宣言するために起こっている、その後、私は、クエリのいずれかのトリガ・ワードに依存を実行し、結果のすべてを返却する必要がある、のように:SQL Serverクエリの場合完全クエリを使用する場合

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 

しかし、これはI以来、エラーが発生します1行以上の結果を含む完全なクエリを実行しようとしています。私はここで立ち往生している。 ifを使用して、事前

答えて

2

にありがとう:

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; 
+0

私は、これはどうもありがとうございました知りませんでした! – fuzunspm

+0

@fuzunspmお手伝いします! – SqlZim

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 
0

次のことを試してみてください...

DECLARE @name VARCHAR(50) 

SET @name = 'value from the script' 
IF (@name = 'orders') 
    (SELECT * FROM orders) 
ELSE IF (@name = 'sales') 
    (SELECT * FROM sales) 
関連する問題