SELECT from nothing?

前端 未结 14 2180
难免孤独
难免孤独 2020-12-24 04:03

Is it possible to have a statement like

SELECT \"Hello world\"
WHERE 1 = 1

in SQL?

The main thing I want to know, is can I SELECT f

相关标签:
14条回答
  • 2020-12-24 04:55

    In Oracle:

    SELECT 'Hello world' FROM dual
    

    Dual equivalent in SQL Server:

    SELECT 'Hello world' 
    
    0 讨论(0)
  • 2020-12-24 04:55

    For DB2:

    `VALUES('Hello world')`
    

    You can do multiple "rows" as well:

    `VALUES('Hello world'),('Goodbye world');`
    

    You can even use them in joins as long as the types match:

    VALUES(1,'Hello world')
    UNION ALL
    VALUES(2,'Goodbye world');
    
    0 讨论(0)
  • 2020-12-24 04:57

    Try this.

    Single:

    SELECT *  FROM (VALUES ('Hello world')) t1 (col1) WHERE 1 = 1
    

    Multi:

    SELECT *  FROM (VALUES ('Hello world'),('Hello world'),('Hello world')) t1 (col1) WHERE 1 = 1
    

    more detail here : http://modern-sql.com/use-case/select-without-from

    0 讨论(0)
  • 2020-12-24 04:57

    There is another possibility - standalone VALUES():

    VALUES ('Hello World');
    

    Output:

    column1
    Hello World
    

    It is useful when you need to specify multiple values in compact way:

    VALUES (1, 'a'), (2, 'b'), (3, 'c');
    

    Output:

    column1     column2
          1     a
          2     b
          3     c
    

    DBFiddle Demo

    This syntax is supported by SQLite/PostgreSQL/DB LUW/MariaDB 10.3.

    0 讨论(0)
  • 2020-12-24 04:59

    You can. I'm using the following lines in a StackExchange Data Explorer query:

    SELECT
    (SELECT COUNT(*) FROM VotesOnPosts WHERE VoteTypeName = 'UpMod' AND UserId = @UserID AND PostTypeId = 2) AS TotalUpVotes,
    (SELECT COUNT(*) FROM Answers WHERE UserId = @UserID) AS TotalAnswers
    

    The Data Exchange uses Transact-SQL (the SQL Server proprietary extensions to SQL).

    You can try it yourself by running a query like:

    SELECT 'Hello world'
    
    0 讨论(0)
  • 2020-12-24 05:04

    In Standard SQL, no. A WHERE clause implies a table expression.

    From the SQL-92 spec:

    7.6 "where clause"

    Function

    Specify a table derived by the application of a "search condition" to the result of the preceding "from clause".

    In turn:

    7.4 "from clause"

    Function

    Specify a table derived from one or more named tables.

    A Standard way of doing it (i.e. should work on any SQL product):

    SELECT DISTINCT 'Hello world' AS new_value
      FROM AnyTableWithOneOrMoreRows
     WHERE 1 = 1;
    

    ...assuming you want to change the WHERE clause to something more meaningful, otherwise it can be omitted.

    0 讨论(0)
提交回复
热议问题