Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the WITH statement doing in this example? I'm trying to randomly generate data

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;
like image 332
cheesysam Avatar asked Sep 11 '09 21:09

cheesysam


1 Answers

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).

like image 158
OMG Ponies Avatar answered Sep 23 '22 09:09

OMG Ponies