我有这个:
SELECT * FROM Person WHERE Age > 5
有没有办法使插入查询成为结果?
结果应如下所示:
INSERT INTO MyTable VALUES (.......)
谢谢
答案 0 :(得分:2)
您在寻找INSERT . . . SELECT
:
INSERT INTO mytable ( . . . ) -- list the columns here
SELECT * -- you should list the columns here too
FROM Person
WHERE Age > 5;
或者仅创建表,使用INTO
:
SELECT p.*
INTO mytable
FROM Person p
WHERE Age > 5;
答案 1 :(得分:0)
以下是一个脚本,该脚本迭代引发当前数据库并为其中的每个表创建一个SELECT INTO
查询。您可以过滤查询以迭代引发所需的表或列,也可以将EXEC(@selectQuery)
替换为Print @selectQuery
以仅获取查询而不执行查询。
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;