Script to create an insert SQL - sql-server

I'm trying to create a script that concatenate various values that in the end it creates a insert script,i'm already made one.
INSERT INTO #SCRPTS
SELECT getdate(),
'INSERT WKF_TpProcesso VALUES (''' + Des_TpProcesso + ''',' + cast(Cod_Func as Varchar(8)) + ',getdate() ,null ,1 ,' + CASE WHEN Id_Sistema IS NULL THEN 'Null' ELSE CAST(Id_Sistema as Varchar(6)) END
+',0,1,0,'+ CASE WHEN Des_CodigoTpProcesso IS NULL THEN 'Null' ELSE '''' + Des_CodigoTpProcesso END +''''+ ','+CAST(Flg_ProxProcesso as Varchar(1))''')'
FROM WKF_TpProcesso
WHERE Des_CodigoTpProcesso = #Des_CodigoTpProcesso
The result is this:
INSERT WKF_TpProcesso VALUES ('Processo Teste',41815,getdate() ,null ,1 ,169,0,1,0, 'PcTestPlus',1)
I'm doing another but can't figure out why doesn't work.
WHILE (exists (select Id_EtapaCampoGen from WKF_EtapaCampoGen Where Id_Etapa = #Id_Etapa ))
INSERT INTO #SCRPTS
SELECT getdate(),
'INSERT WKF_EtapaCampoGen VALUES
(#Id_Etapa' +
','+ ''''+ Des_Label + '''' +
','+ ''''+ Vl_Identificador + '''' +
','+ cast(Flg_Obrigatorio as Varchar(2)) +
',getdate(),'+
',' + CASE WHEN DT_Alteracao IS NULL OR DT_Alteracao = '' THEN 'NULL' ELSE '''' +
',' + cast(FLG_Situacao as Varchar(2))+
',' + '''' + Tipo + '''' +
',' + '''' + Query + '''' +')'
FROM WKF_EtapaCampoGen
I'm having error "Incorrect sintax near FROM",but i cant see what is wrong,someone knows ?
What is funny is that for example the column Des_Label in this is script the DB find the reference of where it comes from,but if i have the error in the from statment how it can find?
It was a END missing in the case when stament,with the end the script returned this.
INSERT WKF_EtapaCampoGen VALUES
(#Id_Etapa,'Areas','CampoComplementar1',0,getdate(),NULL,1,'Lista','select Des_area as Texto, Des_area as valor from wkf_area')

your case expression needs an END
CASE WHEN DT_Alteracao IS NULL OR DT_Alteracao = '' THEN 'NULL' ELSE '''''' END

Related

Using sub-query to generate case statements

What i am trying to accomplish is comparing two rows to each other pointing out the differences from row to row. Each row has quite a few columns and I was trying to make it easily visible for which ones had changed. Code below is my thoughts, but I know this won't work, but is a start.
SELECT
(SELECT concat('Case WHEN T1.', column_name, ' <> T2.', column_name, ' THEN ''', column_name, ' Changed Values('' + CONVERT(varchar(100), T1.', column_name, ') + '', '' + CONVERT(varchar(100), T2.', column_name, ') + '')'' ELSE '''' END AS ', column_name)
FROM information_schema.columns
WHERE table_name = 'Table')
FROM
(
SELECT * FROM Table
WHERE ID = '13'
) AS T1
JOIN
(
SELECT * FROM Table
WHERE ID = '2006'
) AS T2
ON T1.CreateTimeStamp = T2.CreateTimeStamp
I got the idea because below this works fine, but I would like this to be potentially reusable code for other table without having to type out tens or hundreds of columns each time.
SELECT
Case WHEN T1.R1<> T2.R1 THEN 'Changed Values(' + CONVERT(varchar(100),T1.R1) + ', ' + CONVERT(varchar(100),T2.R1) + ')' ELSE '' END AS R1,
Case WHEN T1.R2<> T2.R2 THEN 'Changed Values(' + CONVERT(varchar(100),T1.R2) + ', ' + CONVERT(varchar(100),T2.R2) + ')' ELSE '' END AS R2
FROM
(
SELECT * FROM Table
WHERE ID = '13'
) AS T1
JOIN
(
SELECT * FROM Table
WHERE ID = '2006'
) AS T2
ON T1.CreateTimeStamp = T2.CreateTimeStamp
For the this example please assume CreateTimeStamp always equals each other between the two rows.
You would need to create the whole query as dynamic SQL. Note that I'm using QUOTENAME() to prevent SQL Injection from weirdly named columns. I'm also trying to keep a format for the code, so I won't get headaches when debugging.
DECLARE #SQL NVARCHAR(MAX);
SELECT #SQL = N' SELECT ' + NCHAR(10)
--Concatenate all columns except ID and CreateTimeStamp
+ STUFF(( SELECT REPLACE( CHAR(9) + ',CASE WHEN T1.<<ColumnName>> <> T2.<<ColumnName>> ' + CHAR(10)
+ CHAR(9) + CHAR(9) + 'THEN ''Changed Values('' + CONVERT(varchar(100),T1.<<ColumnName>>) + '', '' + CONVERT(varchar(100),T2.<<ColumnName>>) + '')'' ' + CHAR(10)
+ CHAR(9) + CHAR(9) + 'ELSE '''' END AS <<ColumnName>>', '<<ColumnName>>', QUOTENAME(COLUMN_NAME)) + NCHAR(10)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Table'
AND COLUMN_NAME NOT IN( 'ID', 'CreateTimeStamp')
FOR XML PATH(''), TYPE).value('./text()[1]', 'nvarchar(max)'), 2, 1, '') + NCHAR(10)
--Add rest of the query
+ 'FROM Table AS T1 ' + NCHAR(10)
+ 'JOIN Table AS T2 ON T1.CreateTimeStamp = T2.CreateTimeStamp ' + NCHAR(10)
+ 'WHERE ID = #ID1 ' + NCHAR(10)
+ 'AND ID = #ID2;'
--PRINT for debugging purposes
PRINT #SQL;
--Execute the dynamic built code
EXECUTE sp_executesql #SQL,
N'#ID1 int, #ID2 int',
#ID1 = 13,
#ID2 = 2006;
The concatenation method is explained on this article.

SQL dynamic query check for null, or empty string parameter

I am writing a stored procedure that will be executed from an SSRS report. It receives 2 parameters: SourceID, and ConfirmationNumber but it is not working for all the tests that I am running
this returns recs:[dbo].[GetParkingPaymentInformation] 'PARC', ''
this does not return recs:[dbo].[GetParkingtPaymentInformation] 'PARC', NULL
this does not return recs:[dbo].[GetParkingPaymentInformation] '', '002077770'
this does not return recs:[dbo].[GetParkingPaymentInformation] NULL, '002077770'
this does return recs:[dbo].[GetParkingPaymentInformation] 'PARC', '002077770'
I want the sp to work when one or the other parameter are either null, or blank.
This is what I have so far for code:
SET #s_SQL = 'SELECT d.ID, d.TransactionNumber, h.SourceType, ' + #s_ColumnName + ', d.FirstName, d.LastName,' +
'LTRIM(RTRIM(d.FirstName)) + '' '' + LTRIM(RTRIM(d.LastName)) [Name], '+
'd.PaymentAmount, CONVERT(VARCHAR(10), CAST(d.InitiationDate AS DATE), 101) [InitiationDate]' +
', d.Fee, d.TotalAmount, d.PaymentStatus, d.PaymentType, d.CreditCardType, ' +
'CONVERT(VARCHAR(10), CAST(d.PaymentEffectiveDate AS DATE), 101) [PaymentEffectiveDate]' +
', CONVERT(VARCHAR(10), CAST(d.ProcessDate AS DATE), 101) [ProcessDate], CONVERT(VARCHAR(10), CAST(d.CreatedDate AS DATE), 101) [CreatedDate],' +
'd.CashCode, d.TransConfirmID' +
', d.Phone, d.StreetAddress1, d.StreetAddress2, ' +
'LTRIM(RTRIM(d.StreetAddress1)) + '' '' + CASE WHEN LEN(d.StreetAddress2) > 0 THEN LTRIM(RTRIM(d.StreetAddress2)) ELSE '''' END [Address]' +
', d.City, d.[State], d.ZipFive, d.ZipFour, d.Email ' +
'FROM '+ #s_TableHeader + ' h WITH (NOLOCK) ' +
'INNER JOIN ' + #s_TableDetail + ' d WITH (NOLOCK) ' +
'ON h.ID = d.headerID ' +
'WHERE' +
' ((h.sourcetype = ' + '''' + #s_Source_Type + '''' + ') OR ' + '''' + #s_Source_Type + '''' + ' IS NULL OR ' + '''' + #s_Source_Type + '''' + '= '''')' +
' AND ((d.transconfirmid = ' + '''' + #s_Confirmation_Number + '''' + ') OR ' + '''' + #s_Confirmation_Number + '''' + ' IS NULL OR ' + '''' + #s_Confirmation_Number + '''' + '= '''')'
Any help I can get to figure why my checks are not working, it would be great.
*Please note that your example sql code is incomplete and that you name the parameters slightly different from the variables which makes for difficulty understanding the question. *
It is not without reason that the use of dynamic sql is discouraged even in cases where the dangers of sql injection are negligible. One of the primary reasons for this is that dynamic sql is difficult to write, read and debug. That being said I have often found myself using it to solve for problems within poorly designed systems.
I assume that you have investigated alternatives appropriately.
To reduce the complexity of dynamic sql statements I have found that constructing the statement in a modular way to be a good strategy.
In your particular case the use of an 'if' statement (or some variation) may help reduce the complexity of your dynamic where clause and likely help resolve your problem.
Example:
`
set #sql = 'select....... your select statement..... where'
if (#a_Source_Type is not null and len(#a_Source_Type) > 0)
begin
set #sql += '''' + #a_Source_Type + ''' = some_field and '
end
else
begin
set #sql += ' len(isnull(some_field, '''')) = 0 and '
end
set #sql += ' 1 = 1 '
`
The above attempts to move the comparison operators out of the dynamic sql.
I suggest refactoring your query to use a strategy similar to this example as you may find it easier to identify erroneous code.
the final line of the example has proven useful in circumstances where the resulting dynamic sql statement may or may not have where clauses to append
Try changing your WHERE to something like this:
'where' +
' h.sourcetype = ' + isnull(quotename(nullif(#s_Source_Type, ''), ''''), 'h.sourcetype') +
' AND d.transconfirmid = ' + isnull(quotename(nullif(#s_Confirmation_Number, ''), ''''), 'd.transconfirmid')

Dynamic SQL string returns NULL

I am trying to construct a dynamic SQL statement and for some reason it is not returning the expected results.
This is my query
DECLARE #user_script AS VARCHAR(MAX);
SELECT #user_script += 'IF NOT EXISTS (SELECT [name] FROM sys.database_principals WHERE [name] = '
+ SPACE(1) + '''' + [name] + '''' + ') BEGIN CREATE USER ' + SPACE(1)
+ QUOTENAME([name]) + ' FOR LOGIN ' + QUOTENAME([name])
+ ' WITH DEFAULT_SCHEMA = ' + QUOTENAME([default_schema_name])
+ SPACE(1) + 'END; '
FROM sys.database_principals AS rm
WHERE [type] IN ( 'U', 'S', 'G' )
AND rm.default_schema_name IS NOT NULL;
PRINT ( #user_script );
My problem is that the print statement is not returning anything which I think is because the #user_script variable is NULL.
To evaluate if my table is actually returning results I ran this query (exact copy of the above query without assigning it to a variable) and this query returns 10 rows
SELECT 'IF NOT EXISTS (SELECT [name] FROM sys.database_principals WHERE [name] = '
+ SPACE(1) + '''' + [name] + '''' + ') BEGIN CREATE USER ' + SPACE(1)
+ QUOTENAME([name]) + ' FOR LOGIN ' + QUOTENAME([name])
+ ' WITH DEFAULT_SCHEMA = ' + QUOTENAME([default_schema_name])
+ SPACE(1) + 'END; '
FROM sys.database_principals AS rm
WHERE [type] IN ( 'U', 'S', 'G' )
AND rm.default_schema_name IS NOT NULL;
I tried replacing the function QUOTENAME() with quotes and SPCACE() with actual space but I got the same issue.
I finally checked to see if any of the returned results from the second query is NULL. But none of the rows was a NULL.
Thanks for your help
Try putting a
SET #user_script = ''
on the line before your
select #user_script += ....
You can start the select with
SELECT #user_script = ISNULL(#user_script, '') + ...

Change cursor to CTE

Is it possible to write the following cursor to CTE? It takes an extremely long time to run currently.
Here is my code:
if #ReportSource = 'TAB'
BEGIN
DECLARE yr_cursor CURSOR
FOR
SELECT YEAR, RouteNum, RampInfo, BeginMeasure, EndMeasure, OriginalRoute, Description, CountyDesc, Incidents from #RptParms
OPEN yr_cursor;
FETCH NEXT FROM yr_cursor INTO #Year, #RouteNum, #RampInfo, #BeginMeasure, #EndMeasure, #OriginalRoute, #Description, #CountyDesc, #Incidents;
WHILE (##FETCH_STATUS = 0)
BEGIN
SELECT #sql_str_fred = N'SELECT route_number, beg_measure AS MILELOG, AADT_TOTAL AS VMT, end_measure, RCLINK,YEAR
FROM VW_FRED_AADT_HIST
WHERE route_number = '''+ #RouteNum + '''
and YEAR = '''+ #Year + '''
and FIPS_AND_COUNTY Like ' + '''%' + #CountyDesc + '''
and beg_measure BETWEEN '+ cast(#BeginMeasure as varchar(8)) + ' and ' + cast(#EndMeasure as varchar(8)) + ''
SELECT #sql_str_fred = N' SELECT * from OPENQUERY(EDWGEARS, ''' + REPLACE(#sql_str_fred, '''', '''''') + ''')'
INSERT #freddata (ROUTE_NBR ,
MILELOG ,
VMT ,
END_MEASURE ,
RCLINK ,
YEAR )
EXEC sp_ExecuteSQL #sql_str_fred
FETCH NEXT FROM yr_cursor INTO #Year, #RouteNum, #RampInfo, #BeginMeasure, #EndMeasure, #OriginalRoute, #Description, #CountyDesc, #Incidents;
END
CLOSE yr_cursor
DEALLOCATE yr_cursor
END;
Assume #RptParms - is a table with pameter values and is not huge...
Then all parameters may be combined with query like this:
-- The maximum length of the query string in OPENQUERY is 8 KB !!!
declare
#sql varchar(max) = '
;WITH lst AS (
SELECT * FROM (VALUES
--- values ---
) aa(rn,yr,dsc,m1,m2)
) SELECT route_number, beg_measure AS MILELOG, AADT_TOTAL AS VMT, end_measure, RCLINK,YEAR
FROM VW_FRED_AADT_HIST lst
WHERE route_number = lst.rn
and YEAR = lst.yr
and FIPS_AND_COUNTY Like lst.dsc
and beg_measure BETWEEN lst.m1 and lst.m2
'
select #sql = REPLACE(#sql, '--- values ---', '--- values ---,
(' + ISNULL('''' + RouteNum + '''', 'NULL') -- rn: 1234 --> '1234' or --> NULL
+ ',' + ISNULL('''' + YEAR + '''', 'NULL') -- yn: 1234 --> '1234'
+ ',' + ISNULL('''%'
+ replace(replace(replace(replace(Description
, '[', '[[]')
, '%', '[%]')
, '_', '[_]')
, '''', '''''')
+ '''', 'NULL') -- dsc: a_b[c]%d'e --> '%a[_]b[[]c][%]d''e'
+ ',' + ISNULL('''' + cast(BeginMeasure as varchar(8)) + '''', 'NULL') -- m1: 1234 --> '1234'
+ ',' + ISNULL('''' + cast(EndMeasure as varchar(8)) + '''', 'NULL') -- m2: 1234 --> '1234'
+ ')')
from #RptParms
-- print #sql
/*
;WITH lst AS (
SELECT * FROM (VALUES
--- values ---,
('1234','1234','%a[_]b[[]c][%]d''e','1234','1234'),
('222',NULL,'%abcde','1234','1234'),
(NULL,'1234','%a[_]b[[]c][%]d''e','1234','1234')
) aa(rn,yr,dsc,m1,m2)
) SELECT route_number, beg_measure AS MILELOG, AADT_TOTAL AS VMT, end_measure, RCLINK,YEAR
FROM VW_FRED_AADT_HIST, lst
WHERE route_number = lst.rn
and YEAR = lst.yr
and FIPS_AND_COUNTY Like lst.dsc
and beg_measure BETWEEN lst.m1 and lst.m2
*/
INSERT #freddata (ROUTE_NBR, MILELOG, VMT, END_MEASURE, RCLINK, YEAR)
SELECT *
from OPENQUERY(EDWGEARS, #sql)
Once again:
The maximum length of the query string in OPENQUERY is 8 KB !!!

How can I generate an INSERT script for an existing SQL Server table that includes all stored rows?

I'm looking for a way to generate a "Create and insert all rows" script with SQL Management Studio 2008 R2.
I know that I can create a "create table" script.
I can also create an "insert in" script, but that will only generate a single row with placeholders.
Is there a way to generate an insert script that contains all currently stored rows?
Yes, but you'll need to run it at the database level.
Right-click the database in SSMS, select "Tasks", "Generate Scripts...". As you work through, you'll get to a "Scripting Options" section. Click on "Advanced", and in the list that pops up, where it says "Types of data to script", you've got the option to select Data and/or Schema.
This script generates insert statements of your existing data. This is a stored procedure which you need to run once and then it is tailor made for you.
I tried to find this kind of stuff for a while but wasn't satisfied with the results, so I wrote this stored procedure.
Example:
Exec [dbo].[INS] 'Dbo.test where 1=1'
(1) Here dbo is schema and test is tablename and 1=1 is condition.
Exec [dbo].[INS] 'Dbo.test where name =''neeraj''' * for string
(2) Here dbo is schema and test is tablename and name='neeraj' is condition.
Here is the stored procedure
/*
Authore : neeraj prasad sharma (please dont remove this :))
Example (1) Exec [dbo].[INS] 'Dbo.test where 1=1'
(2) Exec [dbo].[INS] 'Dbo.test where name =''neeraj''' * for string
here Dbo is schema and test is tablename and 1=1 is condition
*/
CREATE procedure [dbo].[INS]
(
#Query Varchar(MAX)
)
AS
SET nocount ON
DECLARE #WithStrINdex as INT
DECLARE #WhereStrINdex as INT
DECLARE #INDExtouse as INT
DECLARE #SchemaAndTAble VArchar(270)
DECLARE #Schema_name varchar(30)
DECLARE #Table_name varchar(240)
DECLARE #Condition Varchar(MAX)
SET #WithStrINdex=0
SELECT #WithStrINdex=CHARINDEX('With',#Query )
, #WhereStrINdex=CHARINDEX('WHERE', #Query)
IF(#WithStrINdex!=0)
SELECT #INDExtouse=#WithStrINdex
ELSE
SELECT #INDExtouse=#WhereStrINdex
SELECT #SchemaAndTAble=Left (#Query,#INDExtouse-1)
SELECT #SchemaAndTAble=Ltrim (Rtrim( #SchemaAndTAble))
SELECT #Schema_name= Left (#SchemaAndTAble, CharIndex('.',#SchemaAndTAble )-1)
, #Table_name = SUBSTRING( #SchemaAndTAble , CharIndex('.',#SchemaAndTAble )+1,LEN(#SchemaAndTAble) )
, #CONDITION=SUBSTRING(#Query,#WhereStrINdex+6,LEN(#Query))--27+6
DECLARE #COLUMNS table (Row_number SmallINT , Column_Name VArchar(Max) )
DECLARE #CONDITIONS as varchar(MAX)
DECLARE #Total_Rows as SmallINT
DECLARE #Counter as SmallINT
DECLARE #ComaCol as varchar(max)
SELECT #ComaCol=''
SET #Counter=1
SET #CONDITIONS=''
INSERT INTO #COLUMNS
SELECT Row_number()Over (Order by ORDINAL_POSITION ) [Count], Column_Name
FROM INformation_schema.columns
WHERE Table_schema=#Schema_name AND table_name=#Table_name
SELECT #Total_Rows= Count(1)
FROM #COLUMNS
SELECT #Table_name= '['+#Table_name+']'
SELECT #Schema_name='['+#Schema_name+']'
While (#Counter<=#Total_Rows )
begin
--PRINT #Counter
SELECT #ComaCol= #ComaCol+'['+Column_Name+'],'
FROM #COLUMNS
WHERE [Row_number]=#Counter
SELECT #CONDITIONS=#CONDITIONS+ ' + Case When ['+Column_Name+'] is null then ''Null'' Else '''''''' + Replace( Convert(varchar(Max),['+Column_Name+'] ) ,'''''''','''' ) +'''''''' end+'+''','''
FROM #COLUMNS
WHERE [Row_number]=#Counter
SET #Counter=#Counter+1
End
SELECT #CONDITIONS=Right(#CONDITIONS,LEN(#CONDITIONS)-2)
SELECT #CONDITIONS=LEFT(#CONDITIONS,LEN(#CONDITIONS)-4)
SELECT #ComaCol= substring (#ComaCol,0, len(#ComaCol) )
SELECT #CONDITIONS= '''INSERT INTO '+#Schema_name+'.'+#Table_name+ '('+#ComaCol+')' +' Values( '+'''' + '+'+#CONDITIONS
SELECT #CONDITIONS=#CONDITIONS+'+'+ ''')'''
SELECT #CONDITIONS= 'Select '+#CONDITIONS +'FRom ' +#Schema_name+'.'+#Table_name+' With(NOLOCK) ' + ' Where '+#Condition
print(#CONDITIONS)
Exec(#CONDITIONS)
Yes, use the commercial but inexpensive SSMS Tools Pack addin which has a nifty "Generate Insert statements from resultsets, tables or database" feature
Just to share, I've developed my own script to do it. Feel free to use it. It generates "SELECT" statements that you can then run on the tables to generate the "INSERT" statements.
select distinct 'SELECT ''INSERT INTO ' + schema_name(ta.schema_id) + '.' + so.name + ' (' + substring(o.list, 1, len(o.list)-1) + ') VALUES ('
+ substring(val.list, 1, len(val.list)-1) + ');'' FROM ' + schema_name(ta.schema_id) + '.' + so.name + ';'
from sys.objects so
join sys.tables ta on ta.object_id=so.object_id
cross apply
(SELECT ' ' +column_name + ', '
from information_schema.columns c
join syscolumns co on co.name=c.COLUMN_NAME and object_name(co.id)=so.name and OBJECT_NAME(co.id)=c.TABLE_NAME and co.id=so.object_id and c.TABLE_SCHEMA=SCHEMA_NAME(so.schema_id)
where table_name = so.name
order by ordinal_position
FOR XML PATH('')) o (list)
cross apply
(SELECT '''+' +case
when data_type = 'uniqueidentifier' THEN 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '])+'''''''' END '
WHEN data_type = 'timestamp' then '''''''''+CONVERT(NVARCHAR(MAX),CONVERT(BINARY(8),[' + COLUMN_NAME + ']),1)+'''''''''
WHEN data_type = 'nvarchar' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE([' + COLUMN_NAME + '],'''''''','''''''''''')+'''''''' END'
WHEN data_type = 'varchar' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE([' + COLUMN_NAME + '],'''''''','''''''''''')+'''''''' END'
WHEN data_type = 'char' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE([' + COLUMN_NAME + '],'''''''','''''''''''')+'''''''' END'
WHEN data_type = 'nchar' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE([' + COLUMN_NAME + '],'''''''','''''''''''')+'''''''' END'
when DATA_TYPE='datetime' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '],121)+'''''''' END '
when DATA_TYPE='datetime2' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '],121)+'''''''' END '
when DATA_TYPE='date' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '],121)+'''''''' END '
when DATA_TYPE='datetimeoffset' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '],121)+'''''''' END '
when DATA_TYPE='geography' and column_name<>'Shape' then 'ST_GeomFromText(''POINT('+column_name+'.Lat '+column_name+'.Long)'') '
when DATA_TYPE='geography' and column_name='Shape' then '''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '])+'''''''''
when DATA_TYPE='bit' then '''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '])+'''''''''
when DATA_TYPE='xml' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE(CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + ']),'''''''','''''''''''')+'''''''' END '
when DATA_TYPE='text' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE(CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + ']),'''''''','''''''''''')+'''''''' END '
WHEN DATA_TYPE='image' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),CONVERT(VARBINARY(MAX),[' + COLUMN_NAME + ']),1)+'''''''' END '
WHEN DATA_TYPE='varbinary' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '],1)+'''''''' END '
WHEN DATA_TYPE='binary' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '],1)+'''''''' END '
when DATA_TYPE='time' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '])+'''''''' END '
ELSE 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE CONVERT(NVARCHAR(MAX),['+column_name+']) END' end
+ '+'', '
from information_schema.columns c
join syscolumns co on co.name=c.COLUMN_NAME and object_name(co.id)=so.name and OBJECT_NAME(co.id)=c.TABLE_NAME and co.id=so.object_id and c.TABLE_SCHEMA=SCHEMA_NAME(so.schema_id)
where table_name = so.name
order by ordinal_position
FOR XML PATH('')) val (list)
where so.type = 'U'

Resources