将sql结果转换为'select UNION select'查询(可导出数据)

时间:2013-01-29 08:28:03

标签: sql sql-server tsql converter

有时我们需要使用我们的客户端数据进行调试,而我们没有时间进行完整的数据库备份,因此我们手动将sql结果转换为静态'select UNION select UNION'的组合,以便我们可以即时使用他们的数据...

示例:

select * from items

结果:

Itemcode     ItemName     Price
Car1         FerrariX     1200.00
Car2         FerrariZ     3000.00
Car3         MustangR     2100.00

我们将它带回到我们这样的环境中:

select 'Car1' as Itemcode, 'FerrariX' as Itemname, 1200.00 as 'Price' UNION
select 'Car2',             'FerrariZ', 3000.00 UNION
select 'Car3',             'MustangR', 2100.00

Posible Stored Procedure Solution:

EXEC spQueryAsStaticData @Query = 'select * from items'

我们如何自动进行此转换?一些存储过程?

2 个答案:

答案 0 :(得分:0)

我使用这样的东西用数据打印文本

DECLARE @i int
DECLARE @employee_id int
Declare @Hash nvarchar(max)
declare @Result nvarchar(max)
Declare @String nvarchar(MAX)
DECLARE @numrows int
DECLARE @employee_table TABLE (
    idx smallint Primary Key IDENTITY(1,1)
    , [ID] int , [Hash] nvarchar(50), Result nvarchar(50)
)


INSERT @employee_table
SELECT Top 5 * FROM [Hlist].[dbo].[MD5]
set @i =0 
set @String = '' 


SET @numrows = (SELECT COUNT(*) FROM @employee_table)

IF @numrows > 0

    WHILE (@i <= (SELECT MAX(idx) FROM @employee_table))
    BEGIN


        -- get the next employee primary key
        SET @employee_id = (SELECT ID  FROM @employee_table WHERE idx = @i)
        SET @Hash = (SELECT Hash  FROM @employee_table WHERE idx = @i)
        SET @Result = (SELECT Result  FROM @employee_table WHERE idx = @i)
        Set @String = coalesce(@String +'Select '+ convert(varchar,@employee_id) + ', ' +@Hash+ ', '+@Result +' Union ', '')

        --
        -- do something with this employee
        --


        -- increment counter for next employee
        SET @i = @i + 1
    END


    Print @String

答案 1 :(得分:0)

最后我们解决了它开发一个小C#应用程序,没有像直接从SQL查询生成它那样有用但是它有效......

如果有人提供SQL解决方案,我们会给他/她

答案