SQL Query在列中显示字符串值

时间:2013-07-10 06:40:13

标签: mysql sql sql-server sql-server-2008 tsql

当我传递参数1

时,我想编写存储过程以获得以下输出
 column_name
 -----------
  option 1
  option 2
  option 3

当我传递参数2时,输出应为

  column_name
  -----------
    option 5
    option 6

是否可以创建过程来获取此输出而不使用任何表?

5 个答案:

答案 0 :(得分:1)

我使用SELECT FROM VALUES执行此类任务。您案件的可能解决方案:

SELECT column_name
FROM (VALUES
         ( 'option 1' )
        ,( 'option 2' )
        ,( 'option 3' )
     ) result (column_name)
WHERE @param = 1

UNION

FROM (VALUES
         ( 'option 5' )
        ,( 'option 6' )
     ) result (column_name)
WHERE @param = 2

答案 1 :(得分:0)

通过使用SELECT和UNION的组合,您可以生成手工构造的表,如下所示:

SELECT 'Option 1' as Option
UNION
SELECT 'Option 2' as Option
UNION
SELECT 'Option 3' as Option

您可以将其与c​​ontrol / flow语句结合使用,以确定应使用哪个SELECT / UNION组合。不幸的是你有MySQL和sql server标签,所以我不能使存储过程的语法更具体,但希望这应该是你觉得舒服的一点!

答案 2 :(得分:0)

无需在数据库中创建任何物理表来存储这些信息。您可以在存储过程中使用临时表或表变量来存储这些数据。您可以创建商店程序,如:

create PROCEDURE temp
@id int
AS
BEGIN
    declare @temptable table (column_name varchar(max))

    if @id = 1
    begin
        insert into @temptable values('option 1');
        insert into @temptable values('option 2');
        insert into @temptable values('option 3');
    end

    if @id = 2
    begin
        insert into @temptable values('option 4');
        insert into @temptable values('option 5');
    end

    select * from @temptable            
END
GO

答案 3 :(得分:0)

CREATE PROCEDURE sp_ArbitraryOutput (@parm Int)
AS
    CASE 
       WHEN COALESCE(@parm, 1) = 1 THEN 
           SELECT "option 1" AS column_name
              UNION 
           SELECT "option 2" AS column_name
              UNION 
           SELECT "option 3" AS column_name
       WHEN @parm = 2 THEN          
           SELECT "option 4" AS column_name
              UNION 
           SELECT "option 5" AS column_name
              UNION 
           SELECT "option 6" AS column_name
    END
GO

答案 4 :(得分:0)

CREATE PROCEDURE uspTest 
(
   @param INT
)
AS
BEGIN

    IF @param = 1
       SELECT 'Option 1' column_name 
       UNION ALL
       SELECT 'Option 2'  
       UNION ALL
       SELECT 'Option 3' 
    ELSE
       SELECT 'Option 5' column_name  
       UNION ALL
       SELECT 'Option 6'  
 END