0

I have this :

SELECT * FROM Person WHERE Age > 5

Is there a way to have as result the insert queries ?

The result should like this :

INSERT INTO MyTable VALUES (.......)

Thanks,

6
  • 2
    Do something like select 'INSERT INTO MyTable VALUES (' || col1 || ', ' col2 etc.... Commented May 21, 2019 at 12:23
  • Or use any of all those tools used to export data. Commented May 21, 2019 at 12:23
  • Sure about the pipe ? select 'INSERT INTO MyTable VALUES (' || Field1|| ',' || Field2 || ')' FROM MyTable give error Commented May 21, 2019 at 12:40
  • || is ANSI SQL for concatenation. Doesn't tsql support it too? Try + instead. Commented May 21, 2019 at 12:42
  • I tried + but didn't work. I use CONCAT should be ok. Commented May 21, 2019 at 12:45

2 Answers 2

2

Are you looking for INSERT . . . SELECT:

INSERT INTO mytable ( . . . )  -- list the columns here
    SELECT *   -- you should list the columns here too
    FROM Person
    WHERE Age > 5;

Or just create the table, use INTO:

SELECT p.*
INTO mytable
FROM Person p
WHERE Age > 5;
Sign up to request clarification or add additional context in comments.

1 Comment

I know that but I want the script.
0

Following is a script which iterate throw the current database and create a SELECT INTO query for each table inside it. you can filter the query to iterate throw the desired tables or columns, or also you can replace the EXEC(@selectQuery) with Print @selectQuery to only get the query without executing it.

DECLARE @selectQuery NVARCHAR(MAX);
DECLARE @tableSchemaName NVARCHAR(MAX);
DECLARE @tableName NVARCHAR(MAX);

DECLARE @schemaId INT;

DECLARE C CURSOR FAST_FORWARD FOR(
SELECT schemas.schema_id,
       sys.schemas.name,
       sys.tables.name
FROM sys.tables
    INNER JOIN sys.schemas
        ON schemas.schema_id = TABLES.schema_id);
OPEN C;
FETCH NEXT FROM C
INTO @schemaId,
     @tableSchemaName,
     @tableName;
WHILE @@FETCH_STATUS = 0
BEGIN

    DECLARE @columns NVARCHAR(MAX);

    SELECT @columns = STRING_AGG(name, ',')
    FROM sys.columns
    WHERE object_id =
    (
        SELECT object_id
        FROM sys.tables
        WHERE name = @tableName
              AND schema_id = @schemaId
    );

    SET @selectQuery
        = N'SELECT ' + @columns + N' INTO ' + @tableSchemaName + N'.' + @tableName + N'2' + N' FROM '
          + @tableSchemaName + N'.' + @tableName;

    EXEC (@selectQuery);
    FETCH NEXT FROM C
    INTO @schemaId,
         @tableSchemaName,
         @tableName;
END;
CLOSE C;
DEALLOCATE C;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.