MS SQL query - if not exists a table - sql

I make a cursor (MSSQL):
CREATE TABLE #temp
(
DB VARCHAR(50),
Tab VARCHAR(50),
[COUNT] INT
)
DECLARE #db_name NVARCHAR (150)
DECLARE #tab1 NVARCHAR (150)
set #tab1 = 'dbo.test'
DECLARE c_db_names CURSOR FOR
SELECT name
FROM sys.databases
WHERE name like '%KNF%'
OPEN c_db_names
FETCH c_db_names INTO #db_name
WHILE ##Fetch_Status = 0
BEGIN
EXEC('
INSERT INTO #temp
SELECT ''' + #db_name + ''',''' + #tab1 + ''',COUNT(*) FROM ' + #db_name + '.' + #tab1 + '
')
FETCH c_db_names INTO #db_name
END
CLOSE c_db_names
DEALLOCATE c_db_names
SELECT * FROM #temp
DROP TABLE #temp
The cursor counts the number of rows in each database table. If there is no such table there is an error.
(1 row(s) affected)
(1 row(s) affected)
Msg 208, Level 16, State 1, Line 2
Invalid object name 'KNF_C.dbo.test'.
(2 row(s) affected)
What is obvious, because the KNF_C database does not have this table. I would like the entire cursor to handle such an exception.
The expected result:
DB Tab COUNT
KNF_A dbo.test 3
KNF_B dbo.test 7
KNF_C no table
I know I should use syntax for example if exist but i dont know how.
Please help to solve this

On SQL Server you can check the existence of an object using OBJECT_ID:
IF OBJECT_ID('dbo.table_name') IS NOT NULL
DO SOMETHING;
Or use INFORMATION_SCHEMA.TABLES instead of sys.databases.

What you have to do is dynamically call the sysobjects table to get if the table exists and then conditionally choose what you want to insert into your temp table.
This probably the code you need:
CREATE TABLE #temp
(
DB VARCHAR(50),
Tab VARCHAR(50),
[COUNT] INT
)
DECLARE #str NVARCHAR(1000)
DECLARE #db_name NVARCHAR (150)
DECLARE #tab1 NVARCHAR (150)
DECLARE #count INT
set #tab1 = 'dbo.test'
DECLARE c_db_names CURSOR FOR
SELECT name
FROM sys.databases
WHERE name like '%KNF%'
OPEN c_db_names
FETCH c_db_names INTO #db_name
WHILE ##Fetch_Status = 0
BEGIN
SET #str = N'Select #internalVariable = (select count(1) from ' + #db_name + '.dbo.sysobjects where name = ''' + replace(#tab1, 'dbo.','') + ''') '
exec sp_executesql
#str, --dynamic query
N'#internalVariable int output', --query parameters
#internalVariable = #count output --parameter mapping
IF ( #count = 1 )
BEGIN
EXEC('
INSERT INTO #temp
SELECT ''' + #db_name + ''',''' + #tab1 + ''',COUNT(*) FROM ' + #db_name + '.' + #tab1 + '
')
END
ELSE
BEGIN
EXEC('
INSERT INTO #temp
SELECT ''' + #db_name + ''',''no table'', null
')
end
FETCH c_db_names INTO #db_name
END
CLOSE c_db_names
DEALLOCATE c_db_names
SELECT * FROM #temp
DROP TABLE #temp

Related

Get name from database table to use in select statement instead of databasename

I have a script that runs through databases with the word VLdata in the databasename. Since the database name and table name is different, I look in the sys login table to look for the login user that has the same name as the table name.
I.e the database name is for example W2595VLData but the table name is "showoffstudios.WgYr"
In all the databases there are a login user with the same name as the table name for the database.
When I run the script below i get the error message "Subquery returned more than 1 value"
I want the below SELECT #DB_LoginName statement to also only run through the databases with "VLData" in the name.
Because I need #DB_LoginName to be the table name and not the database name. So when looking in the database for the column .WgPaySlip it need to be for example W2595.showoffstudios.WgPaySlip.
Any help or tips would be greatly appreciated!
DECLARE database_cursor CURSOR FOR SELECT name FROM sys.sysdatabases where name LIKE '%VLData%
OPEN database_cursor
FETCH NEXT FROM database_cursor INTO #DB_Name
WHILE ##FETCH_STATUS = 0
BEGIN
SELECT #DB_LoginName = (select name as username
from sys.database_principals
where type not in ('A', 'G', 'R', 'X')
and sid is not null
and name != 'guest'
and name != 'dbo'
The original script: This gives me the error
Invalid object name '2544VLData.2544.WgRun'.
because the database name is changed and the table name has another name.
DECLARE #DB_LoginName varchar(200)
DECLARE #Command nvarchar(MAX)
create table #PaySlips
(
WgYr int,
RunNo int,
PaySlips int
);
create table #TotalNumber
(
Firmanavn varchar(100),
Lønnsslipper int,
Sammenstillingsoppgaver int,
Lønnsår int
);
DECLARE database_cursor CURSOR FOR SELECT name FROM sys.sysdatabases where name LIKE '%VLData%'
OPEN database_cursor
FETCH NEXT FROM database_cursor INTO #DB_Name
WHILE ##FETCH_STATUS = 0
BEGIN
SELECT #DB_LoginName = LEFT(#DB_Name,CHARINDEX('VLData',#DB_Name)-1)
SET #Command = 'declare #StartYear int, #EndYear int, #WgYr int, #RunNo int, #PaySlips int, #YearEnd int
set #StartYear = 2020
set #EndYear = 2020
declare WgRun_Cursor cursor for select WgYr, RunNo from ' + '[' + #DB_Name + '].' + '[' + #DB_LoginName + '].WgRun where WgYr >= #StartYear and WgYr <= #EndYear order by WgYr, RunNo
open WgRun_Cursor
fetch next from WgRun_Cursor into #WgYr, #RunNo
while ##FETCH_STATUS = 0
begin
set #PaySlips = isnull((select count (distinct EmpNo) from ' + '[' + #DB_Name + '].' + '[' + #DB_LoginName + '].WgPaySlip where WgYr = #WgYr and WgYr <= #EndYear and RunNo = #RunNo),0)
insert into #PaySlips values(#WgYr, #RunNo, #PaySlips)
fetch next from WgRun_Cursor into #WgYr, #RunNo
end
close WgRun_Cursor
deallocate WgRun_Cursor
declare WgYr_Cursor cursor for select WgYr from ' + '[' + #DB_Name + '].' + '[' + #DB_LoginName + '].WgYr where WgYr >= #StartYear and WgYr <= #EndYear order by WgYr
open WgYr_Cursor
fetch next from WgYr_Cursor into #WgYr
while ##FETCH_STATUS = 0
begin
set #PaySlips = isnull((select sum(PaySlips) from #PaySlips where WgYr = #WgYr),0)
set #YearEnd = isnull((select count (distinct EmpNo) from ' + '[' + #DB_Name + '].' + '[' + #DB_LoginName + '].WgYearEnd where WageYear = #WgYr),0)
insert into #TotalNumber values ((select top 1 Nm from ' + '[' + #DB_Name + '].' + '[' + #DB_LoginName + '].FrmData), #PaySlips, #YearEnd, #WgYr)
fetch next from WgYr_Cursor into #WgYr
end
close WgYr_Cursor
deallocate WgYr_Cursor'
EXEC sp_executesql #Command
FETCH NEXT FROM database_cursor INTO #DB_Name
END
CLOSE database_cursor
DEALLOCATE database_cursor
select * from #TotalNumber
drop table #PaySlips
drop table #TotalNumber ```
Looks like you are seeing multiple logins, or multiple instances of the same login.
Either add a top(1) as I've shown below, or probably better will be to re-write your code to handle each LoginName seperately.
SELECT #DB_LoginName = (select top(1) name as username
from sys.database_principals
where type not in ('A', 'G', 'R', 'X')
and sid is not null
and name != 'guest'
and name != 'dbo'

How can I a variable value into a sql table along with the results from a select statement?

I am trying to insert the results of a SQL select statement into a table, ALONG WITH a value in a SQL variable inside of a FETCH loop. I can do just an insert with the select results, but can't figure out how to insert the variable value along with it.
This is what I've Tried:
IF CURSOR_STATUS('global','CURSOR_ALLDB_NAMES')>=-1
BEGIN
DEALLOCATE CURSOR_ALLDB_NAMES
END
IF OBJECT_ID('tempdb..#TempIDs') IS NOT NULL DROP TABLE #TempIDs
CREATE TABLE #TempIDs(
ID char(256)
,DBName char(256))
DECLARE #DB_NAME nvarchar(256);
DECLARE CURSOR_ALLDB_NAMES CURSOR FOR
SELECT name
FROM Sys.Databases
WHERE name like 'ZM_%'
OPEN CURSOR_ALLDB_NAMES
FETCH CURSOR_ALLDB_NAMES INTO #DB_NAME
WHILE ##Fetch_Status = 0
BEGIN
-- if OBJECT_ID(#DB_NAME + '.dbo.Userlist') is not null EXEC('Insert into #TempIDs (ID) Select ID from '+ #DB_NAME + '.dbo.Userlist')
if OBJECT_ID(#DB_NAME + '.dbo.Userlist') is not null EXEC('Insert into #TempIDs (ID, DBName) Select ID, #DB_NAME from '+ #DB_NAME + '.dbo.Userlist')
FETCH CURSOR_ALLDB_NAMES INTO #DB_NAME
END
Select * from #TempIDs
I get this as a result:
Msg 137, Level 15, State 2, Line 1
Must declare the scalar variable "#DB_NAME".
I've also tried with this which didn't work:
if OBJECT_ID(#DB_NAME + '.dbo.Userlist') is not null EXEC('Insert into #TempIDs (ID, set DBName=''' +#DB_NAME + ''') Select ID from '+ #DB_NAME + '.dbo.Userlist')
FETCH CURSOR_ALLDB_NAMES INTO #DB_NAME
and this which also didn't work:
if OBJECT_ID(#DB_NAME + '.dbo.Userlist') is not null EXEC('Insert into #TempIDs (ID, DBName=''' +#DB_NAME + ''') Select ID from '+ #DB_NAME + '.dbo.Userlist')
FETCH CURSOR_ALLDB_NAMES INTO #DB_NAME
Answer thanks to #JNevil in comments:
Change the SQL statement. This line was changed and it now works:
if OBJECT_ID(#DB_NAME + '.dbo.Userlist') is not null EXEC('Insert into #TempIDs (ID, DBName) Select ID, ''' + #DB_NAME + ''' from ' + #DB_NAME + '.dbo.Userlist')

SQL query to find all references of a particular column in a database?

I need to write some SQL to find all references of a particular column in a database. The column that I'm trying to find references to exists in a different databases. I've found a few examples of finding references of a column that exist in the same database:
In SQL Server, how can I find everywhere a column is referenced?
But I'm having problems figuring out how to do this for a column that exists in a different database. Can you provide the SQL for this? For example purposes, let's refer to the external column I'm trying to find as:
MyExternalDB.MyExternalSchema.MyExternalTable.MyExternalColumn
Ok, just run this and make sure you set your ColumnName variable
USE [master];
GO
IF OBJECT_ID('tempdb..#columns') IS NOT NULL
DROP TABLE #columns;
GO
CREATE TABLE #columns
( databaseName nvarchar(MAX),
columnid int,
columnName nvarchar(MAX),
objectid int,
objectName nvarchar(MAX));
DECLARE #databaseName sysname;
DECLARE #columnName nvarchar(MAX) = 'ColumnName';
DECLARE cur CURSOR LOCAL FORWARD_ONLY STATIC FOR
SELECT [name]
FROM [sys].[databases]
WHERE [state] = 0
AND [name] NOT IN ( 'tempdb', 'master', 'msdb', 'model' );
OPEN cur;
FETCH NEXT FROM cur
INTO #databaseName;
WHILE ( ##FETCH_STATUS != -1 )
BEGIN;
IF ( ##FETCH_STATUS != -2 )
BEGIN;
DECLARE #statement nvarchar(MAX);
SET #statement =N'Use '+ #databaseName +
N';
if EXISTS (SELECT name FROM sys.[columns] WHERE name = ''' + #columnName + ''')
BEGIN;
INSERT [#columns] ( [databaseName], [columnid], [columnName], [objectid], [objectName] )
SELECT ''' + #databaseName + N''',
c.[column_id],
c.[name],
o.[object_id],
o.[name]
FROM sys.[columns] c
INNER JOIN sys.[objects] o
ON [o].[object_id] = [c].[object_id]
WHERE c.[name] = ''' + #columnName + ''';
END;';
EXEC [sys].[sp_executesql] #stmt = #statement;
END;
FETCH NEXT FROM cur
INTO #databaseName;
END;
CLOSE cur;
DEALLOCATE cur;
SELECT * FROM [#columns];

How to do a huge search for Primary Key ID's that is used across the database where these Primary Key ID's have similar values in columns

BackDrop: We are researching why a number of accounts were missed in a process. We have went back to as far as we have data. We now have a rather large list of accounts that for whatever reason were missed. Now this process without going into too much detail is VERY VERY complex and we need to know why these accounts and only these accounts were missed. As any DataBase we have many many automated procedures that run all the time, so there is really at this point no telling what on earth happened to cause these accounts to get missed. My only bet I think at solving this is to find similarities between these accounts. Obviously we have tried looking at the more common places and have since found nothing.
Issue: I want to use SQL to return all the tablenames and columnnames in our database Where these list of accounts have the same value in a column or columns of a table. I have created a query to find tablenames, columns, and so forth but dont know how to bring it all together to create one query that will give me all the results I want. I am certain that a cursor will need to be used and lots of inner joining but I am just not sure how this should be done.
Again:
Lets say I have account numbers 123456 and 654321 and I know our DataBase has 3,000 tables with a column reference to account number with a name of either AccountNumber, AccountNum, or Account. I want to search and find all tables that have a column with the name AccountNumber, AccountNum, or Account that has a value of 123456 or 654321. Then with these tables, for each table I want to take the rows Where the column whether the name be AccountNumber, AccountNum, or Account has a value of either 123456 and 654321 and then for each of those rows I want to check each column of each row to see if the columns on a row for account number 123456 is eqaul to a column on a row for account number 654321 , if so then I want it to return the column name and the tablename. This way I can see what these accounts have in common.
ADVANCED PORTION:
IF some poor soul is able to do the above then I'd also like to create a query that will return
The tablename and when it was updated. I would get the updated value by checking each column in each table and if the column has a type of "timestamp" or a default value of "GetDate()" then that column would be used as updated. In final result set that shows were all changes have happened for those account nubmers it will order by updated.
A first approach, rustic (I'm not that used to T-SQL, I did more PL/SQL), but which may help you going further, AND TESTED IN SQL SERVER 2008. Hope it works in 2005...)
So, we create two procedures, one calling the other
The provided code can only check, in one time
- for 2 differents IDs
- for all concerned fields (Account, AccountNum, AccountNumber)
The idea (checking for AccountNumber column)
Find the tables (in table INFORMATION_SCHEMA.columns, which lists your database tables) which have a column with one of the 3 names provided
For every table found :
create a dynamic query :
select count(*) from <THE_TABLE> where <Account_column_name> IN (123456 654321);
If we have 2 results (mean that our Ids are both present in table), we launch the second procedure, with parameters : #TableName = <THE_TABLE>, #FieldName = <Account_column_name>, #FirstId = 123456, #SecondId = 654321
We find the column names for <THE_TABLE> (again in INFORMATION_SCHEMA.columns).
For every column found :
create a dynamic query
select count(*) from <THE_TABLE> as T1
inner join <THE_TABLE> as T2 on T1.<COLUMN_NAME> = T2.<COLUMN_NAME>
where T1.<Account_column_name>= 123456
and T2.<Account_column_name>= 654321
if count(*) = 1, it means that the same value exists in the same column of the same table for the given ids.
In that case, we print <THE_TABLE> and <THE_COLUMN>
To launch search, in sql management studio, just make
EXEC GetSimilarValuesForFieldAndValue 123456, 654321
and in the "Messages" part, you should have a list of "results".
CREATE procedure [dbo].[GetSimilarValuesForFieldAndValue](#FirstId int, #SecondId int)
AS
DECLARE #sql nvarchar(MAX);
DECLARE #params NVARCHAR(MAX);
DECLARE #Count int;
DECLARE #Name NVARCHAR(MAX);
DECLARE #FieldName NVARCHAR(MAX);
DECLARE db_cursor CURSOR for
select TABLE_NAME, COLUMN_NAME FROM INFORMATION_SCHEMA.columns
where COLUMN_NAME IN('Account', 'AccountNumber', 'AccountNum');
OPEN db_cursor
FETCH next from db_cursor into #Name, #FieldName
while ##FETCH_STATUS = 0
begin
select #sql =
N' SELECT #Count=Count(*) FROM ' + #Name +
N' WHERE ' +#FieldName+' IN (#FirstId,#SecondId)'
SELECT #params = N'#FieldName NVARCHAR(MAX), #FirstId int, #SecondId int, #Count int out'
EXEC sp_executesql #sql, #params, #FieldName, #FirstId, #SecondId, #Count OUT
if (#Count = 2)
begin
exec dbo.CompareFields #Name, #FieldName, #FirstId, #SecondId
end
FETCH NEXT FROM db_cursor INTO #Name, #FieldName
end
close db_cursor
DEALLOCATE db_cursor
GO
The second one :
CREATE procedure [dbo].[CompareFields](#TableName NVARCHAR(MAX), #FieldName NVARCHAR(MAX), #FirstId int, #SecondId int)
as
DECLARE #ColumnName NVARCHAR(MAX)
DECLARE #Sql NVARCHAR(MAX)
DECLARE #Params NVARCHAR(MAX)
DECLARE #Count int
DECLARE cfCursor CURSOR FOR
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = ''+#TableName+' '
AND COLUMN_NAME <> ' '+#FieldName+''
OPEN cfCursor
FETCH next from cfCursor into #ColumnName
while ##FETCH_STATUS = 0
begin
select #Sql =
N' SELECT #Count = count(*) from ' +#TableName + ' T1 '+
N' INNER JOIN ' + #TableName + ' T2 ON T1.' +#ColumnName + ' = T2.' + #ColumnName +
N' WHERE T1.' +#FieldName + ' = '+ CAST(#FirstId as varchar) +
N' AND T2.' + #FieldName + ' = '+CAST(#SecondId as varchar)
SELECT #Params =
N'#TableName VARCHAR(MAX), #ColumnName VARCHAR(MAX), '+
N'#FieldName VARCHAR(MAX), #FirstId int, #SecondId int, #Count int out'
exec sp_executesql #sql, #Params, #TableName, #ColumnName, #FieldName, #FirstId, #SecondId, #Count OUT
if #Count = 1
begin
--print tableName and column Name if value is identic
print 'Table : ' + #TableName + ' : same value for ' + #ColumnName
end
FETCH NEXT FROM cfCursor INTO #ColumnName
end
close cfCursor
DEALLOCATE cfCursor
GO
I actually had to do this for Guids at one point. Here is the script for doing with Guids. One sec and I'll work on modifying it to suit your needs:
DECLARE #table VARCHAR(100)
DECLARE #column VARCHAR(100)
DECLARE #value INT
SET #value = '06B8BD6C-A8EC-4EB3-9562-6666EE86952D'
DECLARE table_cursor CURSOR
FOR select tbl.Name, cols.name as TableName FROM sys.columns cols JOIN
sys.tables tbl on cols.object_id = tbl.object_id
where system_type_id = 36
OPEN table_cursor
FETCH NEXT FROM table_cursor
INTO #table, #column;
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #SQL NVARCHAR(1000)
SET #SQL = 'SELECT ''' + #Table + ''' AS TBL,''' +
#column + ''' AS COL FROM [' + #table + ']
WITH(NOLOCK) WHERE ' + #column + ' = ''' + CAST(#value AS VARCHAR(50)) + ''''
print #sql
EXEC sp_executesql #Sql
FETCH NEXT FROM table_cursor
INTO #table, #column;
END
CLOSE table_cursor
DEALLOCATE table_cursor
Updated to handle for searching on a field name:
DECLARE #table VARCHAR(100)
DECLARE #column VARCHAR(100)
DECLARE #value UNIQUEIDENTIFIER
SET #value = --ENTER YOUR ACCOUNT NUMBER HERE
DECLARE table_cursor CURSOR
select tbl.Name, cols.name as TableName FROM sys.columns cols JOIN
sys.tables tbl on cols.object_id = tbl.object_id
where cols.Name = 'AccountNumber'
OR cols.Name = 'AccountNum' OR cols.Name = 'Account'
OPEN table_cursor
FETCH NEXT FROM table_cursor
INTO #table, #column;
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #SQL NVARCHAR(1000)
SET #SQL = 'SELECT ''' + #Table + ''' AS TBL,''' + #column +
''' AS COL FROM [' + #table + '] WITH(NOLOCK)
WHERE ' + #column + ' = ''' + CAST(#value AS VARCHAR(50)) + ''''
print #sql
EXEC sp_executesql #Sql
FETCH NEXT FROM table_cursor
INTO #table, #column;
END
CLOSE table_cursor
DEALLOCATE table_cursor

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.