How to produce an csv output file from stored procedure in SQL Server

后端 未结 7 828
孤独总比滥情好
孤独总比滥情好 2020-12-03 14:01

Is it possible to generate a csv file from a stored procedure in SQL Server? I created my stored procedure and I want to stored some result as csv, does someone know how to

相关标签:
7条回答
  • 2020-12-03 15:07

    This script exports rows from specified tables to the CSV format in the output window for any tables structure. Hope, the script will be helpful for you -

    DECLARE 
          @TableName SYSNAME
        , @ObjectID INT
    
    DECLARE [tables] CURSOR READ_ONLY FAST_FORWARD LOCAL FOR 
        SELECT 
              '[' + s.name + '].[' + t.name + ']'
            , t.[object_id]
        FROM (
            SELECT DISTINCT
                  t.[schema_id]
                , t.[object_id]
                , t.name
            FROM sys.objects t WITH (NOWAIT)
            JOIN sys.partitions p WITH (NOWAIT) ON p.[object_id] = t.[object_id]
            WHERE p.[rows] > 0
                AND t.[type] = 'U'
        ) t
        JOIN sys.schemas s WITH (NOWAIT) ON t.[schema_id] = s.[schema_id]
        WHERE t.name IN ('<your table name>')
    
    OPEN [tables]
    
    FETCH NEXT FROM [tables] INTO 
          @TableName
        , @ObjectID
    
    DECLARE 
          @SQLInsert NVARCHAR(MAX)
        , @SQLColumns NVARCHAR(MAX)
        , @SQLTinyColumns NVARCHAR(MAX)
    
    WHILE @@FETCH_STATUS = 0 BEGIN
    
        SELECT 
              @SQLInsert = ''
            , @SQLColumns = ''
            , @SQLTinyColumns = ''
    
        ;WITH cols AS 
        (
            SELECT 
                  c.name
                , datetype = t.name
                , c.column_id
            FROM sys.columns c WITH (NOWAIT)
            JOIN sys.types t WITH (NOWAIT) ON c.system_type_id = t.system_type_id AND c.user_type_id = t.user_type_id
            WHERE c.[object_id] = @ObjectID
                AND c.is_computed = 0
                AND t.name NOT IN ('xml', 'geography', 'geometry', 'hierarchyid')
        )
        SELECT 
              @SQLTinyColumns = STUFF((
                SELECT ', [' + c.name + ']'
                FROM cols c
                ORDER BY c.column_id
                FOR XML PATH, TYPE, ROOT).value('.', 'NVARCHAR(MAX)'), 1, 2, '')
            , @SQLColumns = STUFF((SELECT CHAR(13) +
                CASE 
                    WHEN c.datetype = 'uniqueidentifier' 
                        THEN ' + '';'' + ISNULL('''' + CAST([' + c.name + '] AS VARCHAR(MAX)) + '''', ''NULL'')' 
                    WHEN c.datetype IN ('nvarchar', 'varchar', 'nchar', 'char', 'varbinary', 'binary') 
                        THEN ' + '';'' + ISNULL('''' + CAST(REPLACE([' + c.name + '], '''', '''''''') AS NVARCHAR(MAX)) + '''', ''NULL'')' 
                    WHEN c.datetype = 'datetime'
                        THEN ' + '';'' + ISNULL('''' + CONVERT(VARCHAR, [' + c.name + '], 120) + '''', ''NULL'')' 
                    ELSE 
                    ' + '';'' + ISNULL(CAST([' + c.name + '] AS NVARCHAR(MAX)), ''NULL'')'
                END
                FROM cols c
                ORDER BY c.column_id
                FOR XML PATH, TYPE, ROOT).value('.', 'NVARCHAR(MAX)'), 1, 10, 'CHAR(13) + '''' +')
    
        DECLARE @SQL NVARCHAR(MAX) = '    
        SET NOCOUNT ON;
        DECLARE 
              @SQL NVARCHAR(MAX) = ''''
            , @x INT = 1
            , @count INT = (SELECT COUNT(1) FROM ' + @TableName + ')
    
        IF EXISTS(
            SELECT 1
            FROM tempdb.dbo.sysobjects
            WHERE ID = OBJECT_ID(''tempdb..#import'')
        )
            DROP TABLE #import;
    
        SELECT ' + @SQLTinyColumns + ', ''RowNumber'' = ROW_NUMBER() OVER (ORDER BY ' + @SQLTinyColumns + ')
        INTO #import
        FROM ' + @TableName + ' 
    
        WHILE @x < @count BEGIN
    
            SELECT @SQL = STUFF((
            SELECT ' + @SQLColumns + ' + ''''' + '
            FROM #import 
            WHERE RowNumber BETWEEN @x AND @x + 9
            FOR XML PATH, TYPE, ROOT).value(''.'', ''NVARCHAR(MAX)''), 1, 1, '''')
    
            PRINT(@SQL)
    
            SELECT @x = @x + 10
    
        END'
    
        EXEC sys.sp_executesql @SQL
    
        FETCH NEXT FROM [tables] INTO 
              @TableName
            , @ObjectID
    
    END
    
    CLOSE [tables]
    DEALLOCATE [tables]
    

    In the output window you'll get something like this (AdventureWorks.Person.Person):

    1;EM;0;NULL;Ken;J;Sánchez;NULL;0;92C4279F-1207-48A3-8448-4636514EB7E2;2003-02-08 00:00:00
    2;EM;0;NULL;Terri;Lee;Duffy;NULL;1;D8763459-8AA8-47CC-AFF7-C9079AF79033;2002-02-24 00:00:00
    3;EM;0;NULL;Roberto;NULL;Tamburello;NULL;0;E1A2555E-0828-434B-A33B-6F38136A37DE;2001-12-05 00:00:00
    4;EM;0;NULL;Rob;NULL;Walters;NULL;0;F2D7CE06-38B3-4357-805B-F4B6B71C01FF;2001-12-29 00:00:00
    5;EM;0;Ms.;Gail;A;Erickson;NULL;0;F3A3F6B4-AE3B-430C-A754-9F2231BA6FEF;2002-01-30 00:00:00
    6;EM;0;Mr.;Jossef;H;Goldberg;NULL;0;0DEA28FD-EFFE-482A-AFD3-B7E8F199D56F;2002-02-17 00:00:00
    
    0 讨论(0)
提交回复
热议问题