Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate a table with multiple rows just with SELECT statement

If I can do the following select statement to create a table with one value

 SELECT 'myname' AS 'Name' 

this will return a table with column = Name and one value = myname

how can I work around this to return one column with multiple values from just the select statement

I don't want to do this :

 DECLARE @tmp TABLE (Name varchar(50)) 

 INSERT INTO @tmp (Name) VALUES ('myname1'),('myname2') 
    SELECT * FROM @tmp

Just from a single SELECT statement if possible

like image 373
Mina Gabriel Avatar asked Apr 12 '13 19:04

Mina Gabriel


People also ask

How do I create a multi row table in SQL?

If you want to insert more rows than that, you should consider using multiple INSERT statements, BULK INSERT or a derived table. Note that this INSERT multiple rows syntax is only supported in SQL Server 2008 or later. To insert multiple rows returned from a SELECT statement, you use the INSERT INTO SELECT statement.

How do I SELECT multiple row values in SQL?

Multiple Row Subqueries You may use the IN, ANY, or ALL operator in outer query to handle a subquery that returns multiple rows. Contents: Using IN operator with a Multiple Row Subquery. Using NOT IN operator with a Multiple Row Subquery.

How do I create a selection table?

You can create one table from another by adding a SELECT statement at the end of the CREATE TABLE statement: CREATE TABLE new_tbl [AS] SELECT * FROM orig_tbl; MySQL creates new columns for all elements in the SELECT .


3 Answers

If you're wanting to simulate a table with multiple rows just with SELECT statement, this can typically be done with UNION of rows:

SELECT 'myname1' AS 'Name' UNION
SELECT 'myname2' UNION
SELECT 'myname3'
-- etc

Demo: http://www.sqlfiddle.com/#!3/d41d8/12433

like image 83
mellamokb Avatar answered Oct 23 '22 06:10

mellamokb


Or, you can use the multiple VALUES in the SELECT, like:

SELECT [Name]
FROM (VALUES ('myname1'),('myname2')) AS X([name])
like image 43
GilM Avatar answered Oct 23 '22 07:10

GilM


In case you want to simulate sequential data like in your example.You can define a recursive CTE and use it like a table.

Below code will generate 10 records

;With Users as
(
    Select 1 as ID, CAST('Username1' AS varchar(25)) as Name
        union all
    Select ID + 1 , CAST('Username'+CAST(ID+1 AS varchar(5) ) AS varchar(25))
        from Users
        where ID < 10
)
SELECT * FROM Users

Here is SQL Fiddle http://www.sqlfiddle.com/#!3/d41d8/12452

But CTE cannot be used in multiple statements.If you need to use it in multi statements. Then insert data from CTE to Temp Table or Table Variable.

like image 41
ClearLogic Avatar answered Oct 23 '22 06:10

ClearLogic