Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 从SELECT语句导出数据_Sql_Ssms - Fatal编程技术网

Sql 从SELECT语句导出数据

Sql 从SELECT语句导出数据,sql,ssms,Sql,Ssms,我使用的是SSMS 2018,我想将表中的特定数据导出为sql文件中的INSERT语句 我尝试了generatescript选项,但它会导出表中的所有数据,我需要的是导出从select查询返回的非常特定的数据 例如:导出[从条件所在的表中选择*script.sql您可以使用类似的方法 SELECT CONCAT( 'INSERT INTO table_name (col1,col2,col3) VALUES (', col1 , ',', col2 , ',', col3 , ');' ) FR

我使用的是SSMS 2018,我想将表中的特定数据导出为sql文件中的
INSERT
语句

我尝试了generatescript选项,但它会导出表中的所有数据,我需要的是导出从select查询返回的非常特定的数据


例如:导出
[从条件所在的表中选择*script.sql

您可以使用类似的方法

SELECT CONCAT(
'INSERT INTO table_name (col1,col2,col3) VALUES (', col1 , ',', col2 , ',', col3 , ');'
)
FROM table_name
WHERE CONDITION
试试这个:

SELECT * INTO #x FROM TableName where CONDITION
EXEC ConvertQueryToInsert '#x', 'TableName'
首先在数据库中创建ConvertQueryToInsert sp

CREATE PROCEDURE dbo.ConvertQueryToInsert (@input NVARCHAR(max), @target NVARCHAR(max)) AS BEGIN

    DECLARE @fields NVARCHAR(max);
    DECLARE @select NVARCHAR(max);

    -- Get the defintion from sys.columns and assemble a string with the fields/transformations for the dynamic query
    SELECT
        @fields = COALESCE(@fields + ', ', '') + '[' + name +']', 
        @select = COALESCE(@select + ', ', '') + ''''''' + ISNULL(CAST([' + name + '] AS NVARCHAR(max)), ''NULL'')+'''''''
    FROM tempdb.sys.columns 
    WHERE [object_id] = OBJECT_ID(N'tempdb..'+@input);

    -- Run the a dynamic query with the fields from @select into a new temp table
    CREATE TABLE #ConvertQueryToInsertTemp (strings nvarchar(max))
    DECLARE @stmt NVARCHAR(max) = 'INSERT INTO #ConvertQueryToInsertTemp SELECT '''+ @select + ''' AS [strings] FROM '+@input
    exec sp_executesql @stmt

    -- Output the final insert statement 
    SELECT 'INSERT INTO ' + @target + ' (' + @fields + ') VALUES (' + REPLACE(strings, '''NULL''', 'NULL') +')' FROM #ConvertQueryToInsertTemp

    -- Clean up temp tables
    DROP TABLE #ConvertQueryToInsertTemp
    SET @stmt = 'DROP TABLE ' + @input
    exec sp_executesql @stmt
END

最快的方法是
选择一个新表,然后编写脚本。如果您实际上不需要它作为查询,而是为了导入/导出其他地方,那么考虑SSMS也有一个数据导入/导出向导,如果您可以达到这两个服务器。如果没有,则有
bcp
用于以比语句更高效的格式进行批量复制。这旨在向用户展示如何在格式良好的DDL和DML语句中发布数据以提问,但在这里也非常适用: