Question

INSERT INTO files (fileUID, filename)
WITH fileUIDS(fileUID) AS
( VALUES(1) UNION ALL
  SELECT fileUID+1 FROM fileUIDS WHERE fileUID < 1000 )
SELECT fileUID,
       TRANSLATE ( CHAR(BIGINT(RAND() * 10000000000 )), 'abcdefgHij', '1234567890' )
FROM fileUIDS;
Was it helpful?

Solution

The WITH syntax is the same as using either a local temp table or inline view. To my knowledge, it's only supported in SQL Server (2005+, called Common Table Expressions) and Oracle (9i+, called Subquery Factoring). The intended use is for creating a basic view that is used (ie: joined to) multiple times in a single query.

Here's a typical example:

WITH example AS (
     SELECT q.question_id,
            t.tag_name
       FROM QUESTIONS q
       JOIN QUESTION_TAG_XREF qtf ON qtf.question_id = t.question_id
       JOIN TAGS t ON t.tag_id = qtf.tag_id)
SELECT t.title,
       e1.tag_name
  FROM QUESTIONS t
  JOIN example e1 ON e1.question_id = t.question_id

...which will return identical results if you use:

SELECT t.title,
       e1.tag_name
  FROM QUESTIONS t
  JOIN (SELECT q.question_id,
               t.tag_name
          FROM QUESTIONS q
          JOIN QUESTION_TAG_XREF qtf ON qtf.question_id = t.question_id
          JOIN TAGS t ON t.tag_id = qtf.tag_id) e1 ON e1.question_id = t.question_id

The example you provided:

WITH fileUIDS(fileUID) AS ( 
     VALUES(1) 
     UNION ALL
     SELECT t.fileUID+1 
       FROM fileUIDS t
      WHERE t.fileUID < 1000 )
INSERT INTO files 
    (fileUID, filename)
SELECT f.fileUID,
       TRANSLATE ( CHAR(BIGINT(RAND() * 10000000000 )), 'abcdefgHij', '1234567890' )
  FROM fileUIDS f;

...is a recursive one. It's starting at 1, generating 999 fileuids in total (it would be 1,000 if it had started at 0).

OTHER TIPS

WITH x AS (...)

This will take the output of the ... and treat it as a table named x, temporarily.

WITH x AS (...)
SELECT * FROM x

This statement will essentially give you the exact same thing as the ... outputs but it will instead be referenced as the table x

The WITH word is used to create a Common Table Expression (CTE). In this case, it's creating an inline table that the "select fileUID, ..." part is pulling data from.

It is creating CTE (Common Table Expression). This is a basically a table that you don't have to create, drop, or declare in anyway. It will be automatically deleted after the batch has ran.

Check out http://4guysfromrolla.com/webtech/071906-1.shtml for more info.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top