How to update Temp table by providing column name through variable - sql

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.

Related

SQL Server 2012 - Trigger: Operand type clash: int is incompatible with unique identifier

I am writing an audit trigger which saves every change occurred in the table in another table. But I receive this error when I am trying to alter the Users table:
Operand type clash: int is incompatible with unique identifier
The Users table contains a uniqueidentifier column, among others.
Here is the part of the code where the error occurs:
ALTER TRIGGER [dbo].[UsersLogger]
ON [dbo].[Users]
FOR INSERT, DELETE, UPDATE
AS
BEGIN
DECLARE #audit_oldvalue sql_variant;
DECLARE #audit_value sql_variant;
DECLARE #audit_field varchar(100);
DECLARE #sql nvarchar(max);
DECLARE #ParmDefinition nvarchar(max) ;
DECLARE #OutString varchar(max) ;
DECLARE #converted_uid nvarchar(50);
DECLARE #qid int ;
DECLARE #Cinfo VARBINARY(128)
SELECT #Cinfo = Context_Info()
IF #Cinfo = 0x55555
RETURN
DECLARE #Action as char(1);
SET #Action = (CASE WHEN EXISTS(SELECT * FROM INSERTED)
AND EXISTS(SELECT * FROM DELETED)
THEN 'U' -- Set Action to Updated.
ELSE NULL -- Skip. It may have been a "failed delete".
END)
SET #OutString = ''
SELECT *
INTO #tempTrigT
FROM
(SELECT *
FROM deleted
WHERE #Action IN ( 'U', 'D')) A
UNION
(SELECT *
FROM inserted
WHERE #Action = 'I')
SET #sql = ''
if #Action = 'U'
BEGIN
Select #sql = #sql + 'Case when IsNull(i.[' + Column_Name +
'],0) = IsNull(d.[' + Column_name + '],0) then ''''
else ' + quotename(Column_Name, char(39)) + ' + '',''' + ' end +'
from information_schema.columns
where table_name = 'Users' and column_name <>'rowguid' and column_name <>'modifieddate'
set #ParmDefinition = '#OutString varchar(max) OUTPUT'
set #sql = 'Select #OutString = '
+ Substring(#sql,1 , len(#sql) -1) +
' From dbo.Users i '
+ ' inner join #tempTrigT d on
i.id = d.id'
exec sp_executesql #sql, #ParmDefinition, #OutString OUT
END
DECLARE #Items VARCHAR(max)
set #Items = #OutString;
DECLARE #Item VARCHAR(50)
DECLARE #Pos INT
DECLARE #Loop BIT
SELECT #Loop = CASE WHEN LEN(#OutString) > 0 THEN 1 ELSE 0 END
WHILE (SELECT #Loop) = 1
BEGIN
SELECT #Pos = CHARINDEX(',', #OutString, 1)
IF #Pos > 0
BEGIN
SELECT #Item = SUBSTRING(#OutString, 1, #Pos - 1)
SELECT #OutString = SUBSTRING(#OutString, #Pos + 1, LEN(#OutString) - #Pos)
IF (TRY_CONVERT(UNIQUEIDENTIFIER, #Item) is not null)
begin
select #Item = convert(nvarchar(50), #Item)
end
If I had to guess, I'd blame it on
Select #sql = #sql + 'Case when IsNull(i.[' + Column_Name +
'],0) = IsNull(d.[' + Column_name + '],0) then ''''
else ' + quotename(Column_Name, char(39)) + ' + '',''' + ' end +'
from information_schema.columns
where table_name = 'Users' and column_name <>'rowguid' and column_name <>'modifieddate'
It's because you're doing an ISNULL on a UNIQUEIDENTIIFIER column and setting the value to an INT. You could change from ISNULL(i.[ColumnName], 0) to ISNULL(i.[ColumnName], '') however, that is assuming all the columns in your tables are string applicable datatypes. Otherwise, you could do some conditional logic on the replacement value for the ISNULL function by using the [DATA_TYPE] column in that table.

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

T-SQL Dynamic table create

So this is kind of a follow on from my last question
I have a string that looks like this:
Acc_id,Field label,Data point
I'd like to create a table from the above string using somthing like
CREATE TABLE #temp
(Acc_id NVARCHAR(MAX),
Field label REAL,
Data point REAL)
The commas seperate the columns - it needs to be dynamic so if more columns appear they get created in the table.
UPDATE:
this is what I have thus far from the net but i need to make the first column NVARCHAR and the rest REAL rather than the other way round.
declare #path NVARCHAR(MAX)
SET #path = 'c:\temp\Book2.txt'
declare #execSQL nvarchar(1000)
declare #tempstr varchar(1000)
declare #col varchar(1000)
declare #table nvarchar(1000)
-- Create a temp table to with one column to hold the first row of the csv file
CREATE TABLE #tbl (line VARCHAR(1000))
SET #execSQL =
'BULK INSERT #tbl
FROM ''' + #path + '''
WITH (
FIELDTERMINATOR ='','',
FIRSTROW = 1,
ROWTERMINATOR = ''\n'',
LASTROW = 1
)
'
EXEC sp_executesql #stmt=#execSQL
update #tbl set line = REPLACE(line,' ','_') where line like '% %'
SET #col = ''
SET #tempstr = (SELECT TOP 1 RTRIM(REPLACE(Line, CHAR(9), ',')) FROM #tbl)
DROP TABLE #tbl
WHILE CHARINDEX(',',#tempstr) > 0
BEGIN
SET #col=#col + LTRIM(RTRIM(SUBSTRING(#tempstr, 1, CHARINDEX(',',#tempstr)-1))) + ' varchar(100),'
SET #tempstr = SUBSTRING(#tempstr, CHARINDEX(',',#tempstr)+1, len(#tempstr))
END
SET #col = #col + #tempstr + ' real'
IF Object_id('tempdb..##temptable') IS NOT NULL
DROP TABLE #temptable
SET #table = 'create table ##temptable (' + #col + ')'
EXEC sp_executesql #stmt=#table
-- Load data from csv
SET #execSQL =
'BULK INSERT ##temptable
FROM ''' + #path + '''
WITH (
FIELDTERMINATOR ='','',
FIRSTROW = 2,
ROWTERMINATOR = ''\n''
)
'
EXEC sp_executesql #stmt=#execSQL
Thank you
Rob
The Following works perfectly for what I want to do
declare #path NVARCHAR(MAX)
SET #path = 'c:\temp\Book2.txt'
declare #execSQL nvarchar(1000)
declare #tempstr varchar(1000)
declare #col varchar(1000)
declare #table nvarchar(1000)
-- Create a temp table to with one column to hold the first row of the csv file
IF Object_id('tempdb..#tbl') IS NOT NULL
DROP TABLE #tbl
CREATE TABLE #tbl (line VARCHAR(1000))
SET #execSQL =
'BULK INSERT #tbl
FROM ''' + #path + '''
WITH (
FIELDTERMINATOR ='','',
FIRSTROW = 1,
ROWTERMINATOR = ''\n'',
LASTROW = 1
)
'
EXEC sp_executesql #stmt=#execSQL
update #tbl set line = REPLACE(line,' ','_') where line like '% %'
SET #col = ''
SET #tempstr = (SELECT TOP 1 RTRIM(REPLACE(Line, CHAR(9), ',')) FROM #tbl)
DROP TABLE #tbl
SET #col=#col + LTRIM(RTRIM(SUBSTRING(#tempstr, 1, CHARINDEX(',',#tempstr)-1))) + ' nvarchar(max),'
SET #tempstr = SUBSTRING(#tempstr, CHARINDEX(',',#tempstr)+1, len(#tempstr))
WHILE CHARINDEX(',',#tempstr) > 0
BEGIN
SET #col=#col + LTRIM(RTRIM(SUBSTRING(#tempstr, 1, CHARINDEX(',',#tempstr)-1))) + ' nvarchar(max),'
SET #tempstr = SUBSTRING(#tempstr, CHARINDEX(',',#tempstr)+1, len(#tempstr))
END
SET #col = #col + #tempstr + ' real'
IF Object_id('tempdb..##temptable') IS NOT NULL
DROP TABLE ##temptable
SET #table = 'create table ##temptable (' + #col + ')'
EXEC sp_executesql #stmt=#table
-- Load data from csv
SET #execSQL =
'BULK INSERT ##temptable
FROM ''' + #path + '''
WITH (
FIELDTERMINATOR ='','',
FIRSTROW = 2,
ROWTERMINATOR = ''\n''
)
'
EXEC sp_executesql #stmt=#execSQL
select * from ##temptable
I would suggest doing a while loop and concatenating a string together for your table creation. This can beuseful for parsing through delimiter-separated lists. Something similar to the below should get you started.
set #IDList='Field1,Field2,Field3,'
set #i=1
set #pos = patindex('%,%' , #IDList)
while #pos <> 0 begin
-- Loop through Elements
set #CurrentID= isnull(left(#IDList, #pos-1),null)
set #SQLConstructor=#SQLConstructor+',sum('+#CurrentID+') as Column'+#si
--- Reset loop
set #IDList = stuff(#IDList, 1, #pos, '')
set #pos = patindex('%,%' , #IDList)
set #i=#i+1
end

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.