1

This might be a silly question but I have tried several things and can't obtain the result I want.

I am currently testing a very tiny API that consumes data from an SQL Server database. In order to test it I am using a stored procedure that "mocks" a row and returns it. Like this:

CREATE PROCEDURE ONE
    (@FRUITCODE VARCHAR(12))
AS
BEGIN
    SET NOCOUNT ON;

    SELECT
        'BANANA' as NAME
    WHERE 
        @FRUITCODE > 0;
END;

This works fine to simulate one row, but I want to return more rows like this:

NAME
---------
BANANA
STRAWBERRY
MELON

I have tried

CREATE PROCEDURE TWO
    (@FRUITCODE VARCHAR(12))
AS
BEGIN
    SET NOCOUNT ON;

    SELECT
        'BANANA', 'STRAWBERRY', 'MELON' AS NAME
    WHERE @FRUITCODE > 0;
END;

But that results in multiple columns, one is NAME and the others have a blank column name.

I also tried

CREATE PROCEDURE THREE
    (@FRUITCODE VARCHAR(12))
AS
BEGIN
    SET NOCOUNT ON;

    SELECT 'BANANA' AS NAME
    WHERE @FRUITCODE > 0;

    SELECT 'STRAWBERRY' AS NAME
    WHERE @FRUITCODE > 0;

    SELECT 'MELON' AS NAME
    WHERE @FRUITCODE > 0;
END;

But this generates separate "tables" instead of a single one with multiple rows.

Lastly I tried

CREATE EPROCEDURE FOUR
    (@FRUITCODE VARCHAR(12))
AS
BEGIN
    SET NOCOUNT ON;

    SELECT
        'BANANA' AS NAME,
        'STRAWBERRY' AS NAME,
        'MELON' AS NAME
    WHERE @FRUITCODE > 0;
END;

But this returns multiple "NAME" columns.

How can I return several rows? I am using SQL Server.

3
  • 1
    SQL Server 2008 and 2008 R2 reached end of life well over a year ago and are now completely unsupported. You really should be looking at upgrading to a supported version.
    – marc_s
    Commented Jan 14, 2021 at 21:42
  • Search for "Table value constructors". This link should get you started. Scroll down to "Using a Table Value Constructor in a SELECT Statement" section.
    – Alex
    Commented Jan 14, 2021 at 21:56
  • @Alex Thanks for the link, very interesting info.
    – 王子露
    Commented Jan 14, 2021 at 22:37

1 Answer 1

1

We need to use the VALUES table constructor, basically an inline 'invented' table, see the docs on this.
It can also be done with UNION ALL but that is more verbose.

SELECT *
FROM (VALUES
        ('BANANA'),
        ('STRAWBERRY'),
        ('MELON')
) AS v (NAME)
WHERE @FRUITCODE > 0
3
  • At least explain what this functionality is called. Code only answers are frowned upon in SO.
    – Alex
    Commented Jan 14, 2021 at 21:57
  • 1
    @Alex Sorry about that Commented Jan 14, 2021 at 22:01
  • Thanks for the answer! This is what I wanted. I also tried to add multiple columns like this: SELECT * FROM (VALUES ('BANANA','1200'), ('STRAWBERRY','1400'), ('MELON','1500') ) AS v (NAME, FRUITCODE);
    – 王子露
    Commented Jan 14, 2021 at 22:53

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.