2008-06-06

COOL SP: Export data into SQL script

You prabobly can find many versions of this kind of SP. It takes table name and return SQL script which will fill table with data.
It has one extra flag which change script form

INSERT INTO .. VALUES (..)
INSERT INTO .. VALUES (..)
..

TO

INSERT INTO .. SELECT ..
UNION ALL
SELECT ..
UNION ALL
SELECT ..

..

I'm not shure but in Microsoft SQL Server 2008 this feature is buildin.
The code:

IF object_id(N'dbo.TECH_ScriptData', N'P') IS NOT NULL DROP PROCEDURE dbo.TECH_ScriptData
GO

CREATE PROCEDURE dbo.TECH_ScriptData
@tabName varchar(100), -- table to script data
@ex bit = 0 -- if 1 (smaller script, but ) = INSERT INTO .. SELECT ... UNION ALL SELECT ... UNION ALL
-- if 0 = INSERT INTO .. INSERT INTO ..
AS
BEGIN
SET NOCOUNT ON

DECLARE @s nvarchar(max)
DECLARE @sql nvarchar(max)
DECLARE @cols nvarchar(max)
DECLARE @ins nvarchar(max)

SET @cols = ''
SET @ins = ''

------------------------------------------------------
-- Genereate column list
SELECT @cols = @cols + column_name+', ',
@ins = @ins + CASE WHEN data_type IN ('uniqueidentifier','varchar', 'nvarchar', 'nchar', 'char', 'datetime')
THEN '''''''''+'+CASE WHEN data_type = 'uniqueidentifier'
THEN 'CAST('+column_name+' as varchar(50))'
ELSE column_name END+'+'''''''''
ELSE 'CAST('+column_name+' as varchar(50))'
END+' + '','' + '
FROM information_schema.columns
WHERE table_name = @tabName AND COLUMNPROPERTY( OBJECT_ID(@tabName),column_name,'IsIdentity') = 0 -- we dont wont identity columns
ORDER BY ORDINAL_POSITION
SET @s = 'INSERT INTO '+@tabName+' ('+LEFT(@cols, LEN(@cols)-2)+') '

------------------------------------------------------
-- Genereate data
SET @sql = 'SELECT '+LEFT(@ins, LEN(@ins)-9)+' FROM '+@tabName

CREATE TABLE #tt_vals (vals varchar(max))
INSERT INTO #tt_vals
EXEC (@sql)

IF @ex = 0
BEGIN
SELECT @s+' VALUES ('+vals+')' FROM #tt_vals
END ELSE
BEGIN
--SET @s = @s + char(13) + char(10)
PRINT @s
SELECT 'UNION ALL'+char(13)+char(10)+' SELECT '+vals FROM #tt_vals

--PRINT LEFT(@s, LEN(@s)-11)
END

END
GO

No comments: