convert the sql statements to stored procedure - sql

I am trying to convert the below sql statements to stored procedure, which should return me list of delete statements from output parameter.
At present this statement print the sql delete statements on message box of sql server, but i need to make a stored procedure.
The input parameters provide are the table name and the primary key column name and one output parameter which will give the list of sql delete statements.
Can someone help!
if object_id('tempdb..#tmp') is not null
drop table #tmp;
create table #tmp (id int, tablename varchar(256), lvl int, ParentTable varchar(256));
insert into #tmp
exec dbo.usp_SearchFK #table='dbo.M', #debug=0;
declare #where varchar(max) ='where M.id=2' -- if #where clause is null or
empty, it will delete tables as a whole with the right order
declare #curFK cursor, #fk_object_id int;
declare #sqlcmd varchar(max)='', #crlf char(2)=char(0x0d)+char(0x0a);
declare #child varchar(256), #parent varchar(256), #lvl int, #id int;
declare #i int;
declare #t table (tablename varchar(128));
declare #curT cursor;
if isnull(#where, '')= ''
begin
set #curT = cursor for select tablename, lvl from #tmp order by lvl desc
open #curT;
fetch next from #curT into #child, #lvl;
while ##fetch_status = 0
begin -- loop #curT
if not exists (select 1 from #t where tablename=#child)
insert into #t (tablename) values (#child);
fetch next from #curT into #child, #lvl;
end -- loop #curT
close #curT;
deallocate #curT;
select #sqlcmd = #sqlcmd + 'delete from ' + tablename + #crlf from #t ;
print #sqlcmd;
end
else
begin
declare curT cursor for
select lvl, id
from #tmp
order by lvl desc;
open curT;
fetch next from curT into #lvl, #id;
while ##FETCH_STATUS =0
begin
set #i=0;
if #lvl =0
begin -- this is the root level
select #sqlcmd = 'delete from ' + tablename from #tmp where id =
#id;
end -- this is the roolt level
while #i < #lvl
begin -- while
select top 1 #child=TableName, #parent=ParentTable from #tmp
where id <= #id-#i and lvl <= #lvl-#i order by lvl desc, id desc;
set #curFK = cursor for
select object_id from sys.foreign_keys
where parent_object_id = object_id(#child)
and referenced_object_id = object_id(#parent)
open #curFK;
fetch next from #curFk into #fk_object_id
while ##fetch_status =0
begin -- #curFK
if #i=0
set #sqlcmd = 'delete from ' + #child + #crlf +
'from ' + #child + #crlf + 'inner join ' + #parent ;
else
set #sqlcmd = #sqlcmd + #crlf + 'inner join ' + #parent ;
;with c as
(
select child =
object_schema_name(fc.parent_object_id)+'.' +
object_name(fc.parent_object_id), child_col=c.name
, parent =
object_schema_name(fc.referenced_object_id)+'.' +
object_name(fc.referenced_object_id), parent_col=c2.name
, rnk = row_number() over (order by (select null))
from sys.foreign_key_columns fc
inner join sys.columns c
on fc.parent_column_id = c.column_id
and fc.parent_object_id = c.object_id
inner join sys.columns c2
on fc.referenced_column_id = c2.column_id
and fc.referenced_object_id = c2.object_id
where fc.constraint_object_id=#fk_object_id
)
select #sqlcmd =#sqlcmd + case rnk when 1 then ' on '
else ' and ' end
+ #child +'.'+ child_col +'=' + #parent +'.' +
parent_col
from c;
fetch next from #curFK into #fk_object_id;
end --#curFK
close #curFK;
deallocate #curFK;
set #i = #i +1;
end --while
print #sqlcmd + #crlf + #where + ';';
print '';
fetch next from curT into #lvl, #id;
end
close curT;
deallocate curT;
end
go

Related

dynamic script for deleting records with F.K constraints for given table

i need to create script for finding all the tables related with foreign key with the given table and delete the records of the resulted output tables as well as given table with hierarchy dynamically using sql server
This is the stored procedure, i am trying to use for finding all the F.K relationships with hierarchy, but i think its not returning all the foreign key relationships records:
create proc dbo.usp_SearchFK
#table varchar(256) -- use two part name convention
, #lvl int=0 -- do not change
, #ParentTable varchar(256)='' -- do not change
, #debug bit = 1
as
begin
set nocount on;
declare #dbg bit;
set #dbg=#debug;
if object_id('tempdb..#tbl', 'U') is null
create table #tbl (id int identity, tablename varchar(256), lvl int, ParentTable varchar(256));
declare #curS cursor;
if #lvl = 0
insert into #tbl (tablename, lvl, ParentTable)
select #table, #lvl, Null;
else
insert into #tbl (tablename, lvl, ParentTable)
select #table, #lvl,#ParentTable;
if #dbg=1
print replicate('----', #lvl) + 'lvl ' + cast(#lvl as varchar(10)) + ' = ' + #table;
if not exists (select * from sys.foreign_keys where referenced_object_id = object_id(#table))
return;
else
begin -- else
set #ParentTable = #table;
set #curS = cursor for
select tablename=object_schema_name(parent_object_id)+'.'+object_name(parent_object_id)
from sys.foreign_keys
where referenced_object_id = object_id(#table)
and parent_object_id <> referenced_object_id; -- add this to prevent self-referencing which can create a indefinitive loop;
open #curS;
fetch next from #curS into #table;
while ##fetch_status = 0
begin --while
set #lvl = #lvl+1;
-- recursive call
exec dbo.usp_SearchFK #table, #lvl, #ParentTable, #dbg;
set #lvl = #lvl-1;
fetch next from #curS into #table;
end --while
close #curS;
deallocate #curS;
end -- else
if #lvl = 0
select * from #tbl;
return;
end
go
And the below script is using the above SP and creating delete statements:
insert into #tmp
exec dbo.usp_SearchFK #table='dbo.M', #debug=0;
declare #where varchar(max) ='where M.id=2' -- if #where clause is null or empty, it will delete tables as a whole with the right order
declare #curFK cursor, #fk_object_id int;
declare #sqlcmd varchar(max)='', #crlf char(2)=char(0x0d)+char(0x0a);
declare #child varchar(256), #parent varchar(256), #lvl int, #id int;
declare #i int;
declare #t table (tablename varchar(128));
declare #curT cursor;
if isnull(#where, '')= ''
begin
set #curT = cursor for select tablename, lvl from #tmp order by lvl desc
open #curT;
fetch next from #curT into #child, #lvl;
while ##fetch_status = 0
begin -- loop #curT
if not exists (select 1 from #t where tablename=#child)
insert into #t (tablename) values (#child);
fetch next from #curT into #child, #lvl;
end -- loop #curT
close #curT;
deallocate #curT;
select #sqlcmd = #sqlcmd + 'delete from ' + tablename + #crlf from #t ;
print #sqlcmd;
end
else
begin
declare curT cursor for
select lvl, id
from #tmp
order by lvl desc;
open curT;
fetch next from curT into #lvl, #id;
while ##FETCH_STATUS =0
begin
set #i=0;
if #lvl =0
begin -- this is the root level
select #sqlcmd = 'delete from ' + tablename from #tmp where id = #id;
end -- this is the roolt level
while #i < #lvl
begin -- while
select top 1 #child=TableName, #parent=ParentTable from #tmp where id <= #id-#i and lvl <= #lvl-#i order by lvl desc, id desc;
set #curFK = cursor for
select object_id from sys.foreign_keys
where parent_object_id = object_id(#child)
and referenced_object_id = object_id(#parent)
open #curFK;
fetch next from #curFk into #fk_object_id
while ##fetch_status =0
begin -- #curFK
if #i=0
set #sqlcmd = 'delete from ' + #child + #crlf +
'from ' + #child + #crlf + 'inner join ' + #parent ;
else
set #sqlcmd = #sqlcmd + #crlf + 'inner join ' + #parent ;
;with c as
(
select child = object_schema_name(fc.parent_object_id)+'.' + object_name(fc.parent_object_id), child_col=c.name
, parent = object_schema_name(fc.referenced_object_id)+'.' + object_name(fc.referenced_object_id), parent_col=c2.name
, rnk = row_number() over (order by (select null))
from sys.foreign_key_columns fc
inner join sys.columns c
on fc.parent_column_id = c.column_id
and fc.parent_object_id = c.object_id
inner join sys.columns c2
on fc.referenced_column_id = c2.column_id
and fc.referenced_object_id = c2.object_id
where fc.constraint_object_id=#fk_object_id
)
select #sqlcmd =#sqlcmd + case rnk when 1 then ' on ' else ' and ' end
+ #child +'.'+ child_col +'=' + #parent +'.' + parent_col
from c;
fetch next from #curFK into #fk_object_id;
end --#curFK
close #curFK;
deallocate #curFK;
set #i = #i +1;
end --while
print #sqlcmd + #crlf + #where + ';';
print '';
fetch next from curT into #lvl, #id;
end
close curT;
deallocate curT;
end
go

cursor loop - >while (##FETCH_STATUS=0) not going into loop

I have below code:
declare #prefix varchar(50)
set #prefix = 'schema1'
declare #TablesAndIdentifiers table (TableT0 varchar(50), TableX0 varchar(50), IdentifierT0 varchar(50), IdentifierX0 varchar(50))
insert into #TablesAndIdentifiers(TableT0, TableX0, IdentifierT0, IdentifierX0)
values
('table1', 'table2', 'external_Id', 'Key Details | External Id')
declare #TableT varchar(50)
declare #TableX varchar(50)
declare #IdentifierT varchar(50)
declare #IdentifierX varchar(50)
------------------------------------------OUTER LOOP------------------------------------------
declare #OuterCursor cursor
set #OuterCursor = cursor for select * from #TablesAndIdentifiers
open #OuterCursor
fetch next from #OuterCursor into #TableT, #TableX, #IdentifierT, #IdentifierX
while(##FETCH_STATUS = 0)
begin
declare #ColList2 table (ColListT varchar(50), ColListX varchar(50))
insert into #ColList2(ColListT,ColListX)
select ColListT, ColListX
from (
select COLUMN_NAME as ColListT, row_number() over (order by table_name) as r from INFORMATION_SCHEMA.Columns
where table_name = #TableT and COLUMN_NAME!=#IdentifierT) a
full outer join
(select COLUMN_NAME as ColListX, row_number() over (order by table_name) as r from INFORMATION_SCHEMA.Columns
where table_name = #TableX and COLUMN_NAME!=#IdentifierX) b
on a.r = b.r
--Declare and set variables containing the query which will insert the mismatch columns into a new table
--#sqlfull is a concatenation of #sqlpre, #sql, #sqlpost, #sqlwhere, #sqlpregroup, #sqlgroupstatement, #sqlpostgroup
--The reason for this is that #sql is the only part of the query we want to be contained in the loop - the others should run outside of the loop
declare #sqlpre varchar(max)
declare #sql varchar(max)
declare #sqlpost varchar(max)
declare #sqlgroupstatement varchar(max)
declare #sqlpostgroup varchar(max)
declare #sqlfull varchar(max)
set #sqlpre = 'select * from (select '
set #sql = ''
set #sqlpost = #IdentifierT + ' from '+#prefix+'.dbo.' +#TableX +' x inner join '+#prefix+'.dbo.' +#TableT + ' t on t.' +#IdentifierT + ' = x.[' + #IdentifierX +'])dt1 group by '
set #sqlgroupstatement = ''
set #sqlpostgroup = ' ' + #IdentifierT
declare #Cursor cursor, #ColListTvar varchar(100), #ColListXvar varchar(100)
set #Cursor = cursor for select * from #ColList2
open #Cursor
fetch next from #Cursor into #ColListTvar,#ColListXvar
Print 'Before While => ' + CAST(##FETCH_STATUS AS varchar(32))
while (##FETCH_STATUS = 0)
begin
Print 'Inside while -=> ' + CAST(##FETCH_STATUS AS varchar(32))
set #sql = #sql + 'case when t.' +#ColListTvar + ' != x.[' +#ColListXvar + '] then 1 else null end as ' + #ColListTvar+'_mismatch, '
set #sqlgroupstatement = #sqlgroupstatement + #ColListTvar+'_mismatch, '
fetch next from #Cursor into #ColListTvar,#ColListXvar
end
close #Cursor
Print 'After While => ' + CAST(##FETCH_STATUS AS varchar(32))
set #sqlfull = concat(#sqlpre,#sql,#sqlpost,#sqlgroupstatement,#sqlpostgroup)
print(#sqlfull)
--exec(#sqlfull)
declare #ColListMismatch varchar(max)
select #ColListMismatch = coalesce(#ColListMismatch+'_count,' ,'') + column_name
from INFORMATION_SCHEMA.COLUMNS where table_name = 'mismatches_' + #TableT and COLUMN_NAME!=#IdentifierT
-- The last column in the list won't get a '_count' in its name (but it needs it as the rest of the code assumes this is the naming convention)
-- See below for workaround to get round this
--Create table variable containing the list of mismatch columns (in which we want to count the non-nulls - non-null implies there has been a mismatch)
declare #ColListMismatchTable table (ColListM varchar(50))
insert into #ColListMismatchTable(ColListM)
select ColListM
from (select [COLUMN_NAME] as ColListM from INFORMATION_SCHEMA.Columns
where table_name = 'mismatches_'+#TableT and COLUMN_NAME!=#IdentifierT)dt1
--Declare variables for use in queries
declare #sqlpre2 varchar(max)
declare #sqlloop varchar(max)
declare #sqlpost2 varchar(max)
declare #sqlfull2 varchar(max)
-- Select counts from the transformation layer table and the XPLAN table; also select the count of the table produced as a result of the inner join between the two
-- If the migration has functioned correctly, these three counts should all be the same
set #sqlpre2 = 'select countXPLAN, countTransfLayer, countXPLAN-countTransfLayer as CountDiff, countMatchedIdentifiers, '
-- As mentioned above, the "+ #ColListMismatch + '_count into " part of the below is necessary to append the _count to the last variable
+ #ColListMismatch + '_count into '+#prefix+'.[dbo].report_' + #TableT + ' from '
set #sqlloop = ''
set #sqlpost2 = ' select * from ((select count(*) as countTransfLayer from '+#prefix+'.dbo.'+#TableT+')dt1 cross join (select count(*) as countXPLAN from '+#prefix+'.dbo.['+#TableX+'])dt2 cross join (select count(*) as countMatchedIdentifiers from '+#prefix+'.dbo.mismatches_'+#TableT+')dt4)'
------------------------------------------SECOND INNER LOOP------------------------------------------
--Use Cursor to create loop to produce counts for each column in mismatches_*
declare #Cursor2 cursor, #ColListMismatchvar varchar(50)
set #Cursor2 = cursor for select * from #ColListMismatchTable
open #Cursor2
fetch next from #Cursor2 into #ColListMismatchvar
while(##FETCH_STATUS = 0)
begin
-- Select all the counts of non-nulls
set #sqlloop = #sqlloop + '(select count(*) as '+ #ColListMismatchvar + '_count from mismatches_' + #TableT + ' where ' + #ColListMismatchvar + '=1)dt_' + #ColListMismatchvar + ' cross join '
fetch next from #Cursor2 into #ColListMismatchvar
end
-- Remove variables so that they can be reused by the next data entity
delete #ColListMismatchTable
select #ColListMismatch=null
close #Cursor2
print('in loop to execute sqlfull2')
set #sqlfull2 = concat(#sqlpre2,#sqlloop,#sqlpost2)
print(#sqlfull2)
-- exec(#sqlfull2)
print('executed sqlfull2')
fetch next from #OuterCursor into #TableT, #TableX, #IdentifierT, #IdentifierX
end
close #OuterCursor
out put of is:
(1 row(s) affected)
(0 row(s) affected)
Before While => -1
After While => -1
select * from (select external_Id from schema1.dbo.table22 x inner join schama1.dbo.table1 t on t.external_Id = x.[Key Details | External Id])dt1 group by external_Id
(0 row(s) affected)
(0 row(s) affected)
in loop to execute sqlfull2..
The problem i am facing code is not going into while loop of below code
declare #Cursor cursor, #ColListTvar varchar(100), #ColListXvar varchar(100)
set #Cursor = cursor for select * from #ColList2
open #Cursor
fetch next from #Cursor into #ColListTvar,#ColListXvar
Print 'Before While => ' + CAST(##FETCH_STATUS AS varchar(32))
while (##FETCH_STATUS = 0)
begin
Print 'Inside while -=> ' + CAST(##FETCH_STATUS AS varchar(32))
set #sql = #sql + 'case when t.' +#ColListTvar + ' != x.[' +#ColListXvar + '] then 1 else null end as ' + #ColListTvar+'_mismatch, '
set #sqlgroupstatement = #sqlgroupstatement + #ColListTvar+'_mismatch, '
fetch next from #Cursor into #ColListTvar,#ColListXvar
end
close #Cursor
Print 'After While => ' + CAST(##FETCH_STATUS AS varchar(32))
set #sqlfull = concat(#sqlpre,#sql,#sqlpost,#sqlgroupstatement,#sqlpostgroup)
print(#sqlfull)
--exec(#sqlfull)
any suggestions will be much appreciated.
Thanks in advance.
After lot of analysis i found that issue with
select ColListT, ColListX
from (
select COLUMN_NAME as ColListT, row_number() over (order by table_name) as r from INFORMATION_SCHEMA.Columns
where table_name = #TableT and COLUMN_NAME!=#IdentifierT) a
full outer join
(select COLUMN_NAME as ColListX, row_number() over (order by table_name) as r from INFORMATION_SCHEMA.Columns
where table_name = #TableX and COLUMN_NAME!=#IdentifierX) b
on a.r = b.r
Instead of Full outer join if i use inner join it worked.
There was issue with number of columns in 2 tables, one of table has less column than other, that's the reason it wasn't working properly.

Select columns based on values from any table(number of columns is variable) SQL

I have a following table:
Table 1
And I want to show only columns that have at least one value under 50:
Table 2
I need a stored procedure that does this. The trick is that I want to use it on multiple tables but the number of columns can vary from table to table.
Can this be done?
Wish this will have some help.
SET NOCOUNT ON
DECLARE
#tablename VARCHAR(50) = 'Table1',
#valuetocompare INT = 50,
#otherfields VARCHAR(100) = 'Date, Hour,';
DECLARE #t AS TABLE (cname VARCHAR(10), cvalue INT)
DECLARE #sql NVARCHAR(1000);
DECLARE #cname VARCHAR(128);
DECLARE c CURSOR
FOR
SELECT NAME
FROM sys.[columns] AS c
WHERE c.[object_id] = OBJECT_ID(#tablename)
;
OPEN c;
FETCH NEXT FROM c INTO #cname;
WHILE ##FETCH_STATUS = 0
BEGIN
SET #sql = 'select ''' + #cname + ''', ' + #cname + ' from ' + #tablename;
INSERT INTO #t
(
cname,
cvalue
)
EXECUTE (#sql);
FETCH NEXT FROM c INTO #cname;
END
CLOSE c;
DEALLOCATE c;
DECLARE #cnames VARCHAR(100) = '';
WITH dcnames AS (
SELECT DISTINCT cname
FROM #t
WHERE cvalue < #valuetocompare
)
SELECT #cnames = #cnames + cname + ','
FROM dcnames;
IF #cnames = ''
PRINT 'No column value is less than ' + CAST(#valuetocompare AS VARCHAR);
ELSE
BEGIN
SET #sql = 'select ' + #otherfields + LEFT(#cnames, LEN(#cnames) - 1) + ' from ' + #tablename;
EXECUTE (#sql);
END

Check if table has a companyID column

Using SQl how would I check a column of all the tables in #DestinationDatabase if they have a CompanyID using an if statement? within the while loop of the code below?.
I have been told cursors have performance issues but this is the route that somebody above me has chosen to take.
DECLARE #firstLoop BIT
SET #firstLoop = true
DECLARE #Counter INT -- counting variable
----------- Cursor specific code starts here ------------
-- company cursor
declare copyCompanyDataCursor CURSOR fast_forward FOR
SELECT ID from #CompanyIDs;
open copyCompanyDataCursor
fetch next from copyCompanyDataCursor into #Company_Id;
WHILE ##FETCH_STATUS = 0
BEGIN
declare #processorder int;
declare #tablename varchar(500);
-- table cursor
declare copyTableDataCursor CURSOR fast_forward FOR
SELECT processorder,tablename from #TableList4 order by processorder;
open copyTableDataCursor
fetch next from copyTableDataCursor into #processorder, #tablename;
while ##FETCH_STATUS = 0
BEGIN
SET IDENTITY_INSERT [c365online_script1.dbo.tCompany] OFF
-- Does the table have a companyID column? if statement checking for company id
-- if yes then copy data based on companyID in cursor
ELSE
IF #firstLoop > =1 THEN
-- if no check if this is the first time through company loop and copy all data
-- if #firstloop company exists look at information schema
-- insert into c365online_script1.dbo.tCompany(selec
EXEC('INSERT ' + #Destination_Database_Name + '.dbo.' + #tablename + ' SELECT * FROM ' + #Source_Database_Name + '.dbo.' + #tablename + ')')
-- company logic
SET IDENTITY_INSERT [c365online_script1.dbo.tCompany] ON
FETCH NEXT FROM copyTableDataCursor into #processorder,#tablename;
END
close copyTableDataCursor;
Deallocate copyTableDataCursor;
--INSERT INTO c365online_script1.dbo.tCompany
--SELECT *
--FROM production2.tCompany
--WHERE ISNULL(CompanyID, 0) = 0 -- copy all data where id is equal to zero
--#Destination_Database_Name
--
--EXEC(INSERT + #Destination_Database_Name + '.dbo.' + #tablename + ' SELECT * FROM ' + #Source_Database_Name + '.dbo.' + #tablename + ' WHERE ' + #Source_Database_Name + '.dbo.' + #tablename + '.CompanyID = ' + #Company_Id + ')'
SET #firstLoop = false;
FETCH NEXT FROM copyCompanyDataCursor into #Company_Id;
END
CLOSE copyCompanyDataCursor;
DEALLOCATE copyCompanyDataCursor;
You can add this in your WHILE loop. I think this is the solution you're looking for.
IF (
SELECT 1
FROM sys.tables st
INNER JOIN sys.columns sc
ON st.object_id = sc.object_id
WHERE st.NAME = #tablename
AND sc.NAME = #company_id
) > 0
BEGIN
-- your logic here --
END
ELSE
-- other logic here --

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.