将许多表放入SQL Server中的一个表中?

时间:2017-01-19 11:55:47

标签: sql-server

我正在尝试将查询结果插入到新表中。

我正在使用此查询,并希望将结果收集到一个表中。

查询(我在某处找到)看起来像这样:

USE [AdventureWorksDW2012]

SELECT 
    OBJECT_SCHEMA_NAME(T.[object_id],DB_ID()) AS [Schema],
    T.[name] AS [table_name], 
    AC.[name] AS [column_name],
    TY.[name] AS system_data_type, 
    AC.[max_length],
    AC.[precision], AC.[scale], 
    AC.[is_nullable], AC.[is_ansi_padded]
FROM 
    sys.[tables] AS T
INNER JOIN 
    sys.[all_columns] AC ON T.[object_id] = AC.[object_id]
INNER JOIN 
    sys.[types] TY ON AC.[system_type_id] = TY.[system_type_id] 
                   AND AC.[user_type_id] = TY.[user_type_id]
WHERE 
    T.[is_ms_shipped] = 0
ORDER BY 
    T.[name], AC.[column_id];

2 个答案:

答案 0 :(得分:0)

使用INTO子句作为下一个: -

USE [AdventureWorksDW2012]
SELECT OBJECT_SCHEMA_NAME(T.[object_id],DB_ID()) AS [Schema],
T.[name] AS [table_name], AC.[name] AS [column_name],
TY.[name] AS system_data_type, AC.[max_length],
AC.[precision], AC.[scale], AC.[is_nullable], AC.[is_ansi_padded]
Into New_table -- this line is added.
FROM sys.[tables] AS T
INNER JOIN sys.[all_columns] AC ON T.[object_id] = AC.[object_id]
INNER JOIN sys.[types] TY ON AC.[system_type_id] = TY.[system_type_id] AND AC.[user_type_id] = TY.[user_type_id]
WHERE T.[is_ms_shipped] = 0
ORDER BY T.[name], AC.[column_id]

示例代码是

Select *
Into New_table 
From Exist_Table

正如MSDN所说: -

  

SELECT ... INTO在默认文件组中创建一个新表并插入   从查询中得到的行。

答案 1 :(得分:0)

尝试使用INTO这样的句子:

USE [AdventureWorksDW2012]
SELECT OBJECT_SCHEMA_NAME(T.[object_id],DB_ID()) AS [Schema],
T.[name] AS [table_name], AC.[name] AS [column_name],
TY.[name] AS system_data_type, AC.[max_length],
AC.[precision], AC.[scale], AC.[is_nullable], AC.[is_ansi_padded]
INTO dbo.MyNewTable
FROM sys.[tables] AS T
INNER JOIN sys.[all_columns] AC ON T.[object_id] = AC.[object_id]
INNER JOIN sys.[types] TY ON AC.[system_type_id] = TY.[system_type_id]   
                             AND AC.[user_type_id] = TY.[user_type_id]
WHERE T.[is_ms_shipped] = 0
ORDER BY T.[name], AC.[column_id]
;