Incorrect syntax of dynamic sql query - sql

I need help with body of dynamic sql query.
Now, my query like this
declare #query nvarchar(MAX), #preSubQuery nvarchar(200), #subQueryTxt nvarchar(500), #postSubQuery nvarchar(100);
set #postSubQuery = N' ELSE 0 END))'
set #preSubQuery = N' ,SUM(( CASE DATEDIFF(WEEK, pay.dateCreate, back.dateCreate) WHEN ';
set #subQueryTxt = N' THEN
CASE
WHEN ...
THEN 0
WHEN ...
THEN ...
ELSE
CASE
WHEN ...
THEN ...
WHEN ...
THEN ...
ELSE 0
END
END ';
select #query = N'select DATEPART(ISO_WEEK, pay.dateCreate) backWeek ,SUM(pay_and_back.PayActualPrincipalAmt) AS TotalAmount' +
+ N' #preSubQuery' + N' 0' + ' #subQueryTxt' + ' #postSubQuery'
+ N' #preSubQuery' + N' 1' + ' #subQueryTxt' + ' #postSubQuery'
+ N' #preSubQuery' + N' 2' + ' #subQueryTxt' + ' #postSubQuery'
....
+ N' #preSubQuery' + N' 12' + ' #subQueryTxt' + ' #postSubQuery'
select #query = #query + N'
from FinDocPayToPayback pay_and_back
left join FinDocument pay on pay.id = pay_and_back.PayID
left join FinDocument back on back.id = pay_and_back.PaybackID
group by DATEPART(ISO_WEEK, pay.dateCreate) order by 1';
select #query
EXECUTE sp_executesql #query
,N'#preSubQuery nvarchar(200)', #preSubQuery
,N'#subQueryTxt nvarchar(500)', #subQueryTxt
,N'#postSubQuery nvarchar(100)', #postSubQuery;
But i get error Incorrect syntax. First, I need help with this query. Second,
can anyone give more information about how to construct complex dynamic query?

This is your issue. Somewhere in between .... is there, which cause an issue.
Every time you can use print #query, whenever you stuck or get error.
declare #query nvarchar(MAX), #preSubQuery nvarchar(200), #subQueryTxt nvarchar(500), #postSubQuery nvarchar(100);
set #postSubQuery = N' ELSE 0 END))'
set #preSubQuery = N' ,SUM(( CASE DATEDIFF(WEEK, pay.dateCreate, back.dateCreate) WHEN ';
set #subQueryTxt = N' THEN
CASE
WHEN ...
THEN 0
WHEN ...
THEN ...
ELSE
CASE
WHEN ...
THEN ...
WHEN ...
THEN ...
ELSE 0
END
END ';
select #query = N'select DATEPART(ISO_WEEK, pay.dateCreate) backWeek ,SUM(pay_and_back.PayActualPrincipalAmt) AS TotalAmount' +
+ N' #preSubQuery' + N' 0' + ' #subQueryTxt' + ' #postSubQuery'
+ N' #preSubQuery' + N' 1' + ' #subQueryTxt' + ' #postSubQuery'
+ N' #preSubQuery' + N' 2' + ' #subQueryTxt' + ' #postSubQuery'
+ N' #preSubQuery' + N' 12' + ' #subQueryTxt' + ' #postSubQuery'
select #query = #query + N'
from FinDocPayToPayback pay_and_back
left join FinDocument pay on pay.id = pay_and_back.PayID
left join FinDocument back on back.id = pay_and_back.PaybackID
group by DATEPART(ISO_WEEK, pay.dateCreate) order by 1';
select #query
This is actual output of your above query at execution time
SELECT Datepart(iso_week, pay.datecreate) backweek ,
Sum(pay_and_back.payactualprincipalamt) AS totalamount #preSubQuery 0 #subQueryTxt #postSubQuery #preSubQuery 1 #subQueryTxt #postSubQuery #preSubQuery 2 #subQueryTxt #postSubQuery #preSubQuery 12 #subQueryTxt #postSubQuery
FROM findocpaytopayback pay_and_back
LEFT JOIN findocument pay
ON pay.id = pay_and_back.payid
LEFT JOIN findocument back
ON back.id = pay_and_back.paybackid
GROUP BY datepart(iso_week, pay.datecreate)
ORDER BY 1
For complex dynamic query, this is example to understand.
Example1
--declare table1 table ( id int, value varchar(10) )
--drop table Table1
begin tran
create table table1 ( id int, value varchar(10) )
insert into table1 values( 1,'001')
insert into table1 values(2, '002')
insert into table1 values( 3,'003')
insert into table1 values( 4,'004')
create table table2 ( id int, value varchar(10) )
insert into table2 values( 1,'t2value1')
insert into table2 values(2, 't2value2')
insert into table2 values( 3,'t2value3')
insert into table2 values( 4,'t2value4')
-----1st example
declare #sql nvarchar(max) , #temp varchar(50) = '1,2,3'
select * from table1
set #sql = 'select * from table1 where id in ( ' + #temp + ')'
declare #join_table varchar(max)= 'table2', #whereCondition varchar(max) = ' where ' , #orderby varchar(max) = ' t1.id'
select #sql
exec sp_executesql #sql
-----2nd example
set #sql = 'select * from table1 t1 inner join ' + #join_table + ' t2 on t1.id = t2.id '
--if #parameter != null you can give above this condition for
set #whereCondition = #whereCondition + ' t1.id in ( ' + #temp + ')'
--if #orderby != null order by condition
set #orderby = ' order by '+ #orderby
set #sql = #sql + #whereCondition + #orderby
select #sql --you can check that what is wrong by
exec sp_executesql #sql
rollback
**Example2 : Passing parameter into dynamic query **
--begin tran
--create table table1 ( id int, value varchar(10) )
--insert into table1 values( 1,'001')
--insert into table1 values(2, '002')
--insert into table1 values( 3,'003')
--insert into table1 values( 4,'004')
declare #sql nvarchar(max) , #temp nvarchar(50) = '1,2,3', #tempIntSingleValue nvarchar(50) = '2'
select * from table1
set #sql = 'select * from table1 where id in ( ' + #temp + ')'
print #sql
exec sp_executesql #sql
set #sql = 'select * from table1 where id in ( #tempInner)'
print #sql
exec sp_executesql #sql , N'#tempInner int', #tempInner = #tempIntSingleValue
--rollback

Related

Dynamic pivot a 3 column table

I'm trying to use dynamic pivot to have a column containing dates to be the column names.
I want this table:
App Date Count
Excel 2018-05-01 1
Excel 2018-05-02 1
Excel 2018-05-03 2
Word 2018-05-02 3
Word 2018-05-07 5
Word 2018-05-12 2
Paint 2018-05-07 6
to look like this:
2018-05-01 2018-05-02 2018-05-03 2018-05-07 2018-05-12
Excel 1 1 2 0 0
Word 0 3 0 5 2
Paint 0 0 0 6 0
I can't use a normal pivot as I don't know how many or what the dates will actually be. Each app can have a different number of rows. This table isn't just a SELECT * FROM TABLE either, it's made up of subqueries and CTEs so is a little complicated to work with.
Any help is appreciated. Let me know if you need more information.
Using dynamic TSQL:
if OBJECT_ID('dbo.test') is null
create table dbo.test(App varchar(50), [Date] varchar(50), [Count] int)
truncate table dbo.test
insert into dbo.test values
('Excel', '2018-05-01', 1),
('Excel', '2018-05-02', 1),
('Excel', '2018-05-03', 2),
('Word ', '2018-05-02', 3),
('Word ', '2018-05-07', 5),
('Word ', '2018-05-12', 2),
('Paint', '2018-05-07', 6)
declare #dates nvarchar(max)='' --holds all the dates that will become column names
declare #dates_aliases nvarchar(max)='' --holds the headers without NULL values
declare #sql nvarchar(max)='' --contains the TSQL dinamically generated
select #dates = #dates + ', [' + CONVERT(char(10), [date],126)+ ']' from dbo.test
group by [date]
select #dates_aliases = #dates_aliases + ', isnull(['
+ CONVERT(char(10), [date],126)+ '], 0) as ['
+ CONVERT(char(10), [date],126)+ ']'
from dbo.test group by [date]
set #dates = RIGHT(#dates, len(#dates)-2)
set #dates_aliases = RIGHT(#dates_aliases, len(#dates_aliases)-2)
set #sql = #sql + ' select piv.[App], ' + #dates_aliases
set #sql = #sql + ' from '
set #sql = #sql + ' ( '
set #sql = #sql + ' select [App], [Date], [Count] '
set #sql = #sql + ' from dbo.test '
set #sql = #sql + ' ) src '
set #sql = #sql + ' pivot '
set #sql = #sql + ' ( '
set #sql = #sql + ' max([Count]) '
set #sql = #sql + ' for [Date] in ('+#dates+') '
set #sql = #sql + ' ) piv '
exec(#sql)
Results:
Try this:
SELECT A.*
INTO #TEMP
FROM
(
SELECT 'Excel' as app,'2018-05-01' as 'Date',1 as 'Count'
UNION ALL
SELECT 'Excel' as app,'2018-05-02' as 'Date',1 as 'Count'
UNION ALL
SELECT 'Excel' as app,'2018-05-03' as 'Date',2 as 'Count'
UNION ALL
SELECT 'Word' as app,'2018-05-02' as 'Date', 3 as 'Count'
UNION ALL
SELECT 'Word' as app,'2018-05-07' as 'Date', 5 as 'Count'
UNION ALL
SELECT 'Word' as app,'2018-05-12' as 'Date', 2 as 'Count'
UNION ALL
SELECT 'Paint' as app,'2018-05-07' as 'Date', 6 as 'Count'
) as A
ANSWER:
DECLARE #SQL VARCHAR(MAX)
DECLARE #Columns VARCHAR(MAX) = ''
DECLARE #Columns2 VARCHAR(MAX) = ''
SELECT #Columns = #Columns + '[' + a.[Column] + '], '
FROM
(SELECT DISTINCT [date] as [Column]
FROM #TEMP) as a
SELECT #Columns2 = #Columns2 + 'ISNULL([' + a.[Column] + '],0) as [' + a.[column] +'], '
FROM
(
SELECT DISTINCT [date] as [Column]
FROM #TEMP
) as a
SET #Columns2 = Left(#Columns2, Len(#Columns2) - 1)
SET #Columns = Left(#Columns, Len(#Columns) - 1)
SET #SQL = 'SELECT app, ' + #Columns2
+ ' FROM #TEMP PIVOT (Avg (Count) FOR Date IN ('
+ #Columns
+ ')) AS pt '
--PRINT #Columns
EXEC( #SQL )

How to update Temp table by providing column name through variable

I have temp table generated by dynamic SQL query with different column name depends upon data. when I want to update temp table by given hard coded column name it works fine. but when I pass column name by variable it won't works
update #Temp
set #value = ''' + cast(#TempData as nvarchar(max)) + '''
where id = #CUserID
here #value holds column name like [Dusky Legend] this query won't works but
update #Temp
set [Dusky Legend] = ''' + cast(#TempData as nvarchar(max)) + '''
where id = #CUserID
this works properly ,
my problem is I have only way to provide column name by variable
this is my complete code
Declare #MarketID AS NVARCHAR(MAX) = '1.136903880';
Declare #UserID AS NVARCHAR(MAX) = '6a309d84-d1c6-434d-b9df-4f96a74da912';
declare #TempData as numeric = 1111111111;
declare ##values as NVARCHAR(MAX) ='';
DECLARE #colsSelect AS NVARCHAR(MAX);
DECLARE #colsLoop AS NVARCHAR(MAX);
DECLARE #query AS NVARCHAR(MAX);
SELECT #colsSelect = STUFF((SELECT distinct ',' +
'00' + ' as ' + QUOTENAME(name)
from RunnersInfoes AS t where marketID =#MarketID
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
, 1, 1, '');
SELECT #colsLoop = STUFF((SELECT distinct ',' +
QUOTENAME(name)
from RunnersInfoes AS t where marketID =#MarketID
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
, 1, 1, '');
--print #colsLoop
set #query=
'
;with cte
as
(
select
id, ParentId,0 AS Level,Share ,AccountTypeName,FirstName
from dbo.View_UserProfile
where View_UserProfile.id = ' + '''' + #UserID + '''' +'
union all
select
t.id, t.ParentId,Level + 1 AS Level,t.Share,t.AccountTypeName ,t.FirstName
from View_UserProfile t
inner join cte on t.ParentId = cte.id)
SELECT ID,AccountTypeName as Type,FirstName as Name, ' + #colsSelect + ' into #Temp from cte as t
--exec tempdb..sp_help #Temp
Declare #CUserID AS NVARCHAR(MAX)
DECLARE dynamic_cursor CURSOR FOR
select ID from #Temp
OPEN dynamic_cursor
FETCH NEXT FROM dynamic_cursor INTO #CUserID
WHILE ##FETCH_STATUS = 0
BEGIN
declare #pos as numeric = 0
declare #len as numeric = 0
declare #value as varchar(255)
WHILE CHARINDEX('','', ''' + #colsLoop +''', #pos+1)>0
BEGIN
set #len = CHARINDEX('','', ''' + #colsLoop +''', #pos+1) - #pos
set #value = SUBSTRING(''' + #colsLoop +''', #pos, #len)
PRINT #value
update #Temp set [Dusky Legend] = ''' + cast(#TempData as nvarchar(max)) + ''' where id = #CUserID
set #pos = CHARINDEX('','', ''' + #colsLoop +''', #pos+#len) +1
END
--print' + cast(#TempData as nvarchar(max)) +'
--update #Temp set [Dusky Legend] =''' + cast(#TempData as nvarchar(max)) + ''' where id = #CUserID
FETCH NEXT FROM dynamic_cursor INTO #CUserID
END
CLOSE dynamic_cursor
DEALLOCATE dynamic_cursor
select * from #Temp
'
execute (#query)
You need dynamic SQL.
declare #value varchar(64) = '[Dusky Legend]'
declare #TempData varchar(max) = 'some value'
declare #CUSerID int = 14
declare #sql varchar(max)
set #sql = '
update #Temp
set ' + #value + ' = ' + cast(#TempData as nvarchar(max)) + '
where id = ' + cast(#CUserID as varchar(256))
print(#sql)
--exec(#sql)
Side note, you may need a global TempTable depending on how you are doing this.

Select table and column dynamically based on other table rows

I have following table and values,
Tb_name column_name1 column_name2
Citator_KTLO_CC Date_Created Date_Modified
Citator_KTLO_QA Date_Created Date_Modified
I want to select dynamically column from table, so the result is like this:
Select Date_Created,Date_Modified from Citator_KTLO_CC
and in next loop it will select for second row, like
Select Date_Created,Date_Modified from Citator_KTLO_QA
How can i do this by using dynamic sql ?
any example are appreciated.
here is an example of how to do this.
Since you dont post many info I just assume that the table containing all the tablenames is called 'tables'
Also this will only work if all tables have the same column types.
-- create a test table you dont need this
create table tables (tb_name varchar(100) primary key, field1 varchar(100), field2 varchar(100))
-- fill my test table you dont need this
insert into tables values ('table1', 'field1', 'field2')
insert into tables values ('table2', 'foo1', 'foo2')
insert into tables values ('table3', 'test1', 'test2')
-- this is the actual code you need, replace the names with your real names
declare #sql varchar(max) = ''
declare #tb_name varchar(100) = ''
declare #field1 varchar(100) = ''
declare #field2 varchar(100) = ''
declare myCursor cursor for
select tb_name, field1, field2 from tables -- dont know how your table is called
open myCursor
fetch next from myCursor into #tb_name, #field1, #field2
while ##FETCH_STATUS = 0
begin
set #sql = #sql + ' select ' + #field1 + ', ' + #field2 + ' from ' + #tb_name + ' union all '
fetch next from myCursor into #tb_name, #field1, #field2
end
close myCursor
deallocate myCursor
select #sql = left(#sql, len(#sql) - 10)
exec (#sql)
EDIT:
using a where clause is possible but things will get more complicated
declare #something date = getdate()
set #sql = #sql + ' select ' + #field1 + ', ' + #field2 + ' from ' + #tb_name + ' where ' + #field1 + ' = ' + #something + ' union all '
You can use the example above to build what you need just play with it.
EDIT:
using a where clause with a date format
declare #something date = getdate()
set #sql = #sql + ' select ' + #field1 + ', ' + #field2 + ' from ' + #tb_name + ' where ' + #field1 + ' = ''' + CONVERT(varchar(8), #something, 112) + ''' union all '
DECLARE #SQL VARCHAR(1000);
SET #SQL = '
SELECT *
FROM Citator_KTLO_CC
UNION ALL
SELECT *
FROM Citator_KTLO_QA;'
EXEC (#SQL);
How about something like this. If you've more than two cols, you can use dynamic sql to generate a list of cols to then generate more dynamic sql instead of hard coding.
DROP TABLE #Test
CREATE TABLE #Test
(Tb_name NVARCHAR(15),
column_name1 NVARCHAR(12),
column_name2 NVARCHAR(13));
INSERT INTO #Test VALUES
('Citator_KTLO_CC','Date_Created','Date_Modified'),
('Citator_KTLO_QA','Date_Created','Date_Modified');
DECLARE #SQL NVARCHAR(MAX)
SET #SQL = (SELECT STUFF((SELECT ' UNION ALL SELECT ' + Cols + ' FROM '+TbL
FROM (SELECT QUOTENAME(Tb_name) TBL,
QUOTENAME(column_name1) + ', '+
QUOTENAME(column_name2) Cols
FROM #Test) Blah
FOR XML PATH('')),1,10,''))
PRINT #SQL
EXEC sys.sp_executesql #SQL
Try this..
For selecting one row if you are running in aloop
DECLARE #sql NVARCHAR(4000)
SELECT #sql = ' select ' + column_name_1 + ',' + column_name2 + ' from ' + Tb_name
FROM < yourtable >
EXEC (#sql)
OR
DECLARE #sql NVARCHAR(4000)
SELECT #sql = 'union all select ' + column_name_1 + ',' + column_name2 + ' from ' + Tb_name
FROM < yourtable >
SET #sql =stuff(#sql,1,10,'')
EXEC (#sql)
DECLARE #ColumnList1 VARCHAR(MAX) = '''''';
DECLARE #ColumnList2 VARCHAR(MAX) = '''''';
DECLARE #ColumnNameFromTable1 VARCHAR(50);
DECLARE #ColumnNameFromTable2 VARCHAR(50);
DECLARE MyCursor1 CURSOR
FOR
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Citator_KTLO_CC'
ORDER BY ORDINAL_POSITION
DECLARE MyCursor2 CURSOR
FOR
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Citator_KTLO_QA'
ORDER BY ORDINAL_POSITION
OPEN MyCursor1
OPEN MyCursor2
FETCH NEXT FROM MyCursor1 INTO #ColumnNameFromTable1;
WHILE ##FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM MyCursor2 INTO #ColumnNameFromTable2;
SET #ColumnList1 = #ColumnList1 + ',' + #ColumnNameFromTable1
SET #ColumnList2 = #ColumnList2 + ',' + #ColumnNameFromTable2
FETCH NEXT FROM MyCursor1 INTO #ColumnNameFromTable1;
END
CLOSE MyCursor1;
DEALLOCATE MyCursor1;
CLOSE MyCursor2;
DEALLOCATE MyCursor2;
EXEC ('SELECT ' + #ColumnList1 + ' FROM Citator_KTLO_CC UNION ALL SELECT ' +
#ColumnList2 + ' FROM Citator_KTLO_QA ')

Return Row Count Using Dynamic SQL

I'm trying to run the following Dynamic SQL statement:
#Tbl, #Fld, and #LookupValue have all been set according to Table to search, Field (Or Column) to search and column value to compare.
DECLARE #Sql AS VARCHAR(500)
SET #Sql = 'SELECT COUNT(*)
FROM ' + #Tbl +
' WITH (NOLOCK)
WHERE ' + #Fld + ' = ''' + #LookupValue + ''''
EXEC(#Sql)
I want to store the result into a variable so I can check to see if there are any returned rows. This statement is in the middle of a WHILE construct that is checking several tables and fields.
If records are found, then I want to display:
SET #Sql = 'SELECT ' + #Fld +
' FROM ' + #Tbl +
' WITH (NOLOCK)
WHERE ' + #Fld + ' = ''' + #LookupValue + ''''
EXEC(#Sql)
Yes, you can store it in a typed variable and use sp_executesql like
DECLARE #Sql AS NVARCHAR(500);
DECLARE #cnt INT;
SET #Sql = 'SELECT #cnt = COUNT(*)
FROM ' + #Tbl +
' WITH (NOLOCK)
WHERE ' + #Fld + ' = ''' + #LookupValue + '''';
EXEC sp_executesql #Sql, N'#cnt INT OUTPUT', #cnt OUTPUT;
SELECT #cnt;
you can create a temporary table and store the count value.
if object_id('tempdb.#mycount') is null
create table #mycount ( countVal int);
DECLARE #Sql AS VARCHAR(500)
SET #Sql = 'INSERT INTO #mycount
SELECT COUNT(*)
FROM ' + #Tbl +
' WITH (NOLOCK)
WHERE ' + #Fld + ' = ''' + #LookupValue + ''''
EXEC(#Sql)
select countVal from #mycount
-- once the temp table usage is done, you can delete it
drop table #mycount

Creating A Script To Replicate A Table And Its Contents?

I know you can create a script to replicate a table using:
right click table > script table as > create to > new query editor window
But how can I generate a script that contains a bunch of insert commands for each row in the table?
Table1
Id1, Row1
Id2, Row2
Id3, Row3
Insert into Table1 values(Row1);
Insert into Table1 values(Row2);
Insert into Table1 values(Row3);
I ended up doing this
right click database > Tasks > Generate Scripts ... > selected the tables > in the advanced options I set "Types of data to script" to "Schema and data"
Select
'Insert into Table (
IntField1
StringField2
Column3)
values (' +
IntField1 + ',' +
+ '''' + StringField2 + ''',' +
Column2 + ')' as InsertQuery
From Table
Something like this, just remember if your string contains a single quote you will need to make sure you replace it like this replace(stringfield, '''', '''''')
So this isnt super pretty cuz I kind of took one of my sp's and hacked it up for this. But basically this will take any table and print a series of insert statements into a table called tbl_text (which you would need to create)
The arguments are the table name and the table ID from sysobjects
--this is how you get the tbl_id
SELECT id FROM sysobjects WHERE type = 'U' AND name = 'tablename'
CREATE PROCEDURE dbo.sp_export_table
#tblhdr varchar(100),
#tblID varchar(100)
AS
SET NOCOUNT ON
IF object_id('tempdb..##temptable') IS NOT NULL
BEGIN
DROP TABLE ##temptable
END
DECLARE #identity bit
DECLARE #typestmt nvarchar(100)
DECLARE #typeval int
DECLARE #rowstmt nvarchar(1000)
DECLARE #rowID varchar(50)
DECLARE #orderby nvarchar(100)
DECLARE #clmnstmt varchar(200)
DECLARE #clmnhdr varchar(50)
DECLARE #clmnstring varchar(1000)
DECLARE #valuestmt nvarchar(200)
DECLARE #valuestring nvarchar(3000)
DECLARE #value nvarchar(1000)
DECLARE #insertstmt varchar(1000)
DECLARE #params nvarchar(100)
DECLARE #param2 nvarchar(100)
SELECT #rowstmt = N'SELECT TOP 1 #inside_var = name FROM syscolumns WHERE id = ' + #tblID + ' ORDER BY colorder'
SELECT #params = N'#inside_var NVARCHAR(1000) OUTPUT'
EXEC sp_executesql #rowstmt, #params, #inside_var = #orderby OUTPUT
SELECT #rowstmt = 'SELECT *, ROW_NUMBER() OVER (ORDER BY ' + #orderby + ') AS row INTO ##temptable FROM ' + #tblhdr
exec(#rowstmt)
IF object_id('tempdb..##temptable') IS NOT NULL
BEGIN
DECLARE row_cursor CURSOR FOR
SELECT row FROM ##temptable
OPEN row_cursor
FETCH NEXT FROM row_cursor
INTO #rowID
--if table has identity and has records write identity_insert on
SET #identity = 0
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE OBJECTPROPERTY(OBJECT_ID(TABLE_NAME),
'TableHasIdentity') = 1 AND TABLE_TYPE = 'BASE TABLE'
AND TABLE_NAME = #tblhdr) AND EXISTS(SELECT * FROM ##temptable)
BEGIN
SET #identity = 1
INSERT INTO dbo.tbl_text VALUES('SET IDENTITY_INSERT dbo.' + #tblhdr + ' ON')
END
WHILE ##FETCH_STATUS = 0
BEGIN
SELECT #clmnstmt = 'DECLARE column_cursor CURSOR FOR SELECT name FROM syscolumns WHERE id = ' + #tblID + ' ORDER BY colorder'
exec(#clmnstmt)
OPEN column_cursor
FETCH NEXT FROM column_cursor
INTO #clmnhdr
SELECT #clmnstring = '('
SELECT #valuestring = '('
WHILE ##FETCH_STATUS = 0
BEGIN
IF #clmnhdr <> 'row'
BEGIN
SELECT #clmnstring = #clmnstring + #clmnhdr + ','
SELECT #valuestmt = N'SELECT #inside_var = ' + #clmnhdr + ' FROM ##temptable WHERE row = ' + #rowID
EXEC sp_executesql #valuestmt, #params, #inside_var = #value OUTPUT
SELECT #typestmt = N'SELECT #inside_var2 = xtype FROM syscolumns WHERE name = ''' + #clmnhdr + ''' AND id = ' + #tblID
SELECT #param2 = N'#inside_var2 INT OUTPUT'
EXEC sp_executesql #typestmt, #param2, #inside_var2 = #typeval OUTPUT
IF #typeval NOT IN (48,52,56,59,60,62,104,108,122,127)
BEGIN
SET #value = REPLACE(#value,'''','''''')
SET #value = '''' + #value + ''''
SET #value = ISNULL(#value, '''''')
END
IF NOT (#typeval = 34)
BEGIN
SELECT #valuestring = #valuestring + #value + ','
END
ELSE
BEGIN
SELECT #valuestring = #valuestring + '''''' + ','
END
END
FETCH NEXT FROM column_cursor
INTO #clmnhdr
END
SET #clmnstring = LEFT(#clmnstring, LEN(#clmnstring) - 1)
SET #valuestring = LEFT(#valuestring, LEN(#valuestring) - 1)
INSERT INTO dbo.tbl_text VALUES('INSERT INTO dbo.' + #tblhdr + ' ' + #clmnstring + ') VALUES' + #valuestring + ')')
FETCH NEXT FROM row_cursor
INTO #rowID
CLOSE column_cursor
DEALLOCATE column_cursor
END
--if it wrote identity_insert on, turn it off
IF (#identity = 1)
BEGIN
INSERT INTO dbo.tbl_text VALUES('SET IDENTITY_INSERT dbo.' + #tblhdr + ' OFF')
END
CLOSE row_cursor
DEALLOCATE row_cursor
END
IF object_id('tempdb..##temptable') IS NOT NULL
BEGIN
DROP TABLE ##temptable
END
GO
If you've got an account on SSC, you can use the script I published last year. It works without cursors an it enables custom filtering.
http://www.sqlservercentral.com/scripts/Script+Data/65998/
Hope this helps
Assuming Row is an INT NOT NULL. You could write a SELECT statement that outputs SQL;
SELECT N'INSERT INTO Table1 VALUES (' + CAST(Row AS NVARCHAR(10)) + N');'
FROM Table1
Then output your results to text.