1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

お試しクエリにも便利なVALUES構築子

Posted at

VALUES構築子はINSERT文以外でも使えます(SQL-99から)。

SELECT
    *
FROM
    (VALUES
        (1, 'Alice')
      , (2, 'Bob')
      , (3, 'Carol')
    ) AS users
        (id, name)
id name
1 Alice
2 Bob
3 Carol

もちろん、JOINすることもできます。

SELECT
    users.id
  , users.name
  , comments.comment
FROM
    (VALUES
        (1, 'Alice')
      , (2, 'Bob')
      , (3, 'Carol')
	) AS users
        (id, name)
LEFT OUTER JOIN
    (VALUES
        (1, 'Hello')
      , (3, 'World')
	) AS comments
        (user_id, comment)
    ON users.id = comments.user_id
id name comment
1 Alice Hello
2 Bob NULL
3 Carol World

UPDATEやDELETEはできないものの、一時テーブルを作らずに済むので楽です。

データ型はどうなるの?

SQL Serverで値の情報を調べるには、SQL_VARIANT_PROPERTY関数を使います。

SELECT
    *
  , SQL_VARIANT_PROPERTY(id, 'BaseType') id_type
  , SQL_VARIANT_PROPERTY(name, 'BaseType') name_type
FROM
    (VALUES
        (1, 'Alice')
      , (2, 'Bob')
      , (3, 'Carol')
    ) AS users
        (id, name)
id name id_type name_type
1 Alice int varchar
2 Bob int varchar
3 Carol int varchar

値に応じて、適当なデータ型が与えられるようです。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?