简体   繁体   English

从 SELECT 语句导出数据

[英]Exporting data from a SELECT Statement

I'm using SSMS 2018, and i want to export specific data from a table as INSERT statement in a sql file.我正在使用 SSMS 2018,我想将表中的特定数据导出为 sql 文件中的INSERT语句。

I tried the generate Script option but it exports all the data from the table, what I need is to export a very specific data returned from a select query.我尝试了生成脚本选项,但它导出了表中的所有数据,我需要导出从 select 查询返回的非常具体的数据。

ex: EXPORT [Select * From Table WHERE CONDITION] >> script.sql例如:EXPORT [Select * From Table WHERE CONDITION] >> script.sql

you can use something like this你可以使用这样的东西

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

try this:尝试这个:

SELECT * INTO #x FROM TableName where CONDITION
EXEC ConvertQueryToInsert '#x', 'TableName'

first create ConvertQueryToInsert sp in your database首先在您的数据库中创建 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM