Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Possible to set explicit type in CTE?

I can create a CTE that contains named columns of inferred type with:

WITH employees(name, salary) AS (
    SELECT 'Paul', 10000
) SELECT * FROM employees

Is there a way to specify the type in the CTE itself, for example doing:

WITH employees(name , salary DECIMAL(8,2)) AS (
    SELECT 'Paul', 10000
) SELECT * FROM employees

Or do I have to always do it within the SELECT statement, such as:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

WITH employees(name, salary) AS (
    SELECT 'Paul', DECIMAL(8,2) '10000'
) SELECT * FROM employees

>Solution :

You can cast the values in the CTE:

WITH employees(name, salary) AS (
  select 'Paul', cast(10000 as decimal(8,2))
) 
SELECT * 
FROM employees

Or using a VALUES clause which removes the need for a UNION if multiple rows are needed.

WITH employees(name, salary) AS (
  values 
     ('Paul', cast(10000 as decimal(8,2))), 
     ('Peter', 5000)
) 
SELECT * 
FROM employees

The cast is only needed in the first row, because that defines the data type of that column for all other rows from the VALUES clause (or a SELECT with a UNION)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading