Syntax Issue while Declaring select statement into a variable - sql

If I run the select statement its working fine but if I defined into a variable then I am getting syntax error.
Declare #a varchar(2550)
SET #a='
SELECT 'ALTER DATABASE ' + CAST(DB_NAME() AS VARCHAR(50)) + ' MODIFY FILE ( NAME = ' +
QUOTENAME( df.name,'''') + ', NEWNAME = ''' +
QUOTENAME( DB_NAME()) +
+ CASE
WHEN df.type_desc = 'ROWS' AND df.file_id = 1 THEN '.mdf'' )'
WHEN df.type_desc = 'LOG' THEN '_log.ldf'' )'
WHEN df.type_desc = 'ROWS' AND df.file_id != 1 THEN '.ndf'' )'
END
FROM sys.database_files df'
select #a
Error:
Msg 102, Level 15, State 1, Line 38 Incorrect syntax near ' +
CAST(DB_NAME() AS VARCHAR(50)) + '.

It's a combination of typing errors and wrong use of SET and/or SELECT. If I understand you correctly, you may try to use the following statement:
DECLARE #a varchar(2550)
SELECT #a =
'ALTER DATABASE ' +
CAST(DB_NAME() AS VARCHAR(50)) +
' MODIFY FILE ( NAME = ' +
QUOTENAME( df.name,'''') + ', NEWNAME = ''' +
QUOTENAME( DB_NAME()) +
CASE
WHEN df.type_desc = 'ROWS' AND df.file_id = 1 THEN '.mdf'' )'
WHEN df.type_desc = 'LOG' THEN '_log.ldf'' )'
WHEN df.type_desc = 'ROWS' AND df.file_id != 1 THEN '.ndf'' )'
END
FROM sys.database_files df
SELECT #a
As an important note, when you use SELECT #local_variable and the SELECT statement returns more than one value, the variable is assigned the last value that is returned. So if you want to generate a complex statement for all database files, you need to concatenate the returned rows (using FOR XML PATH or STRING_AGG()). In this case, as #GordonLinoff commented, you may declare the #a variable as nvarchar(max):
DECLARE #a nvarchar(max) = N''
SELECT #a = (
SELECT
N'ALTER DATABASE ' +
CAST(DB_NAME() AS VARCHAR(50)) +
N' MODIFY FILE ( NAME = ' +
QUOTENAME( df.name,'''') +
N', NEWNAME = ''' +
QUOTENAME( DB_NAME()) +
CASE
WHEN df.type_desc = 'ROWS' AND df.file_id = 1 THEN N'.mdf'' )'
WHEN df.type_desc = 'LOG' THEN N'_log.ldf'' )'
WHEN df.type_desc = 'ROWS' AND df.file_id != 1 THEN N'.ndf'' )'
END +
N';'
FROM sys.database_files df
FOR XML PATH('')
)
SELECT #a

I think you're looking for something like this
declare #a nvarchar(max);
with file_cte as (
select
N'ALTER DATABASE ' + quotename(db_name()) +
N' MODIFY FILE ( NAME = ' + quotename( df.name,'''') +
N', NEWNAME = ''' + quotename(db_name()) +
case when df.type_desc = N'ROWS' AND df.file_id = 1 then N'.mdf'' )'
when df.type_desc = N'LOG' THEN N'_log.ldf'' )'
when df.type_desc = N'ROWS' AND df.file_id != 1 then N'.ndf'' )' end string
from sys.database_files df)
select #a=concat(string_agg(string, ';'), ';')
from file_cte;
select #a;

Related

Msg 156, Level 15, State 1, Line 1 Incorrect syntax near the keyword 'SELECT'. Msg 102, Level 15, State 1, Line 1 Incorrect syntax near '.'

I try to run 2 dynamic SQL, but I have an error that the syntax is incorrect. When I make a select for every parameter that I declare, there is no problem. But when I try to execute the string I have these erroes. Any help?
Msg 156, Level 15, State 1, Line 1 Incorrect syntax near the keyword 'SELECT'. Msg 102, Level 15, State 1, Line 1 Incorrect syntax near '.'
--declare Variablen für die Prozedur
declare #DispoColumn nvarchar(max) = (select STRING_AGG(col.name, ', ') within group (order by col.column_id)
FROM sys.objects obj
JOIN sys.columns col on col.object_id = obj.object_id
JOIN sys.types typ ON col.user_type_id=typ.user_type_id
Where obj.name = #Tabelle and obj.schema_id = 5
GROUP BY obj.name);
declare #ID nvarchar(150) = (select MAX(CASE WHEN col.column_id = 1 THEN col.name ELSE NULL END)
FROM sys.objects obj
JOIN sys.columns col on col.object_id = obj.object_id
JOIN sys.types typ ON col.user_type_id=typ.user_type_id
Where obj.name = #Tabelle and obj.schema_id = 5
GROUP BY obj.name);
declare #EFREdispoUpdate nvarchar(max)
declare #ESFdispoUpdate nvarchar(max)
declare #ESFdispoInsert nvarchar(max)
declare #EFREdispoInsert nvarchar(max)
--Update der Tabellen
set #ESFdispoUpdate = 'UPDATE ESF.' + #Tabelle + ' SET GUELTIG_BIS = GETDATE() WHERE GUELTIG_BIS = ''9999-12-31'' AND ' + #ID + ' IN ( SELECT '
+ #ID + 'FROM ( SELECT ' +#DispoColumn + ' FROM ESF.' + #Tabelle + ' WHERE GUELTIG_BIS = ''9999-12-31''' + ' EXCEPT SELECT ' + #DispoColumn + ' SF.' + #Tabelle + ') as alt );'
+ ' UPDATE DISPO.T_TABELLEN SET ANZ_GEANDERT = (SELECT COUNT(*) FROM ESF.'+#Tabelle + ' WHERE GUELTIG_BIS = GETDATE())'
+ 'WHERE SCH_NAME = ''ESF'' AND TAB_NAME = ''' +#Tabelle + ''';';
set #EFREdispoUpdate = 'UPDATE EFRE.' + #Tabelle + ' SET GUELTIG_BIS = GETDATE() WHERE GUELTIG_BIS = ''9999-12-31'' AND ' + #ID + ' IN ( SELECT '
+ #ID + 'FROM ( SELECT ' +#DispoColumn + ' FROM EFRE.' + #Tabelle + ' WHERE GUELTIG_BIS = ''9999-12-31''' + ' EXCEPT SELECT ' + #DispoColumn + ' SF.' + #Tabelle + ') as alt );'
+ ' UPDATE DISPO.T_TABELLEN SET ANZ_GEANDERT = (SELECT COUNT(*) FROM EFRE.'+#Tabelle + ' WHERE GUELTIG_BIS = GETDATE())'
+ 'WHERE SCH_NAME = ''EFRE'' AND TAB_NAME = ''' +#Tabelle + ''';';
EXEC sp_executesql #ESFdispoUpdate;
EXEC sp_executesql #EFREdispoUpdate;
Your issue is because on the second line of your set statements, you forgot a space before FROM
Other minor changes
Added brackets to column names just in case column has special character like a space
Removed unnecessary GROUP BY clauses in subqueries
Changed second subquery from CASE WHEN to WHERE so it's more intuitive
DECLARE #Tabelle NVARCHAR(100) = 'YourTable'
declare #DispoColumn nvarchar(max) = (select STRING_AGG(QUOTENAME(col.name), ', ') within group (order by col.column_id)
FROM sys.objects obj
JOIN sys.columns col on col.object_id = obj.object_id
WHERE obj.name = #Tabelle AND obj.schema_id = 5
);
declare #ID nvarchar(150) = (SELECT QUOTENAME(col.name)
FROM sys.objects obj
JOIN sys.columns col on col.object_id = obj.object_id
Where obj.name = #Tabelle AND obj.schema_id = 5
AND col.column_id = 1
);
select #DispoColumn,#ID
declare #EFREdispoUpdate nvarchar(max)
,#ESFdispoUpdate nvarchar(max)
,#ESFdispoInsert nvarchar(max)
,#EFREdispoInsert nvarchar(max)
set #ESFdispoUpdate = 'UPDATE ESF.' + #Tabelle + ' SET GUELTIG_BIS = GETDATE() WHERE GUELTIG_BIS = ''9999-12-31'' AND ' + #ID + ' IN ( SELECT '
+ #ID + ' FROM ( SELECT ' +#DispoColumn + ' FROM ESF.' + #Tabelle + ' WHERE GUELTIG_BIS = ''9999-12-31''' + ' EXCEPT SELECT ' + #DispoColumn + ' SF.' + #Tabelle + ') as alt );'
+ ' UPDATE DISPO.T_TABELLEN SET ANZ_GEANDERT = (SELECT COUNT(*) FROM ESF.'+#Tabelle + ' WHERE GUELTIG_BIS = GETDATE())'
+ 'WHERE SCH_NAME = ''ESF'' AND TAB_NAME = ''' +#Tabelle + ''';';
set #EFREdispoUpdate = 'UPDATE EFRE.' + #Tabelle + ' SET GUELTIG_BIS = GETDATE() WHERE GUELTIG_BIS = ''9999-12-31'' AND ' + #ID + ' IN ( SELECT '
+ #ID + ' FROM ( SELECT ' +#DispoColumn + ' FROM EFRE.' + #Tabelle + ' WHERE GUELTIG_BIS = ''9999-12-31''' + ' EXCEPT SELECT ' + #DispoColumn + ' SF.' + #Tabelle + ') as alt );'
+ ' UPDATE DISPO.T_TABELLEN SET ANZ_GEANDERT = (SELECT COUNT(*) FROM EFRE.'+#Tabelle + ' WHERE GUELTIG_BIS = GETDATE())'
+ 'WHERE SCH_NAME = ''EFRE'' AND TAB_NAME = ''' +#Tabelle + ''';';
/*Use for debugging*/
SELECT #ESFdispoUpdate
SELECT #EFREdispoUpdate

String literal in SQL query field

I'd like to do a stuff command in string literal query and it give some error
The query without string literal working:
SELECT apGr.*, 'Name: ' + apGr.GroupDesc + ' | Group: ' + apGr.GroupName GroupFull ,
abc = STUFF
(
(
SELECT ',' + appGrMn.Email
FROM APP_GroupManager As appGrMn
-- You only want to combine rows for a single ID here:
WHERE appGrMn.GroupId = apGr.GroupId
FOR XML PATH (''), TYPE
).value('.', 'varchar(max)')
, 1, 1, '')
FROM App_Group apGr
WHERE apGr.GroupId = 239
The query as string literal failed:
DECLARE #WhereQuery NVARCHAR(200) = ''
DECLARE #Query NVARCHAR(500)
SET #GroupId = 5
-- Insert statements for procedure here
IF(#GroupId IS NOT NULL)
BEGIN
PRINT(#GroupId)
SET #WhereQuery = 'WHERE apGr.GroupId = ' + #GroupId
END
ELSE IF (#SystemId IS NOT NULL)
BEGIN
SET #WhereQuery = 'WHERE apGr.SystemId = ' + #SystemId
END
ELSE IF (#GroupName IS NOT NULL)
BEGIN
SET #WhereQuery = 'WHERE apGr.GroupName = ''' + #GroupName + ''''
END
SET #Query = 'SELECT ''Name: '' + apGr.GroupDesc + '' | Group: '' + apGr.GroupName GroupFull ,
abc = STUFF
(
(
SELECT '','' + appGrMn.AdministratorMail
FROM APP_GroupManager As appGrMn
-- You only want to combine rows for a single ID here:
WHERE appGrMn.GroupId = apGr.GroupId
FOR XML PATH (''), TYPE
).value(''.'', varchar(max))
, 1, 1, '') ' +
'FROM App_Group apGr ' +
'JOIN T_SensitiveLevel AS tSen ON tSen.SensitiveLevelId = apGr.SensitiveLevelId ' + #WhereQuery
PRINT #Query
EXEC(#Query)
END
The printed query looks:
5
SELECT 'Name: ' + apGr.GroupDesc + ' | Group: ' + apGr.GroupName GroupFull ,
abc = STUFF
(
(
SELECT ',' + appGrMn.AdministratorMail
FROM APP_GroupManager As appGrMn
-- You only want to combine rows for a single ID here:
WHERE appGrMn.GroupId = apGr.GroupId
FOR XML PATH ('), TYPE
).value('.', varchar(max))
, 1, 1, ') FROM App_Group apGr JOIN T_SensitiveLevel AS tSen ON tSen.SensitiveLevelId = apGr.SensitiveLevelId WHERE apGr.GroupId = 2
It not append the #WhereQuery as it should and the error is:
Msg 102, Level 15, State 1, Line 20
Incorrect syntax near '.'.
Any help on this would be appreciated.
There were some '' related syntax error. instead of '' you need to use '''' when expecting ('') in output. Where clause is truncated since #query became larger then it's length(500). I have made some changes in the query please check:
DECLARE #WhereQuery NVARCHAR(200) = ''
DECLARE #Query NVARCHAR(2000)
declare #GroupId NVARCHAR(500)
declare #SystemId NVARCHAR(500)
declare #GroupName NVARCHAR(500)
set #GroupName='a'
SET #GroupId = 5
-- Insert statements for procedure here
IF(#GroupId IS NOT NULL)
BEGIN
PRINT(#GroupId)
SET #WhereQuery = 'WHERE apGr.GroupId = ' + #GroupId
END
ELSE IF (#SystemId IS NOT NULL)
BEGIN
SET #WhereQuery = 'WHERE apGr.SystemId = ' + #SystemId
END
ELSE IF (#GroupName IS NOT NULL)
BEGIN
SET #WhereQuery = 'WHERE apGr.GroupName = ''' + #GroupName + ''''
END
SET #Query = 'SELECT ''Name: '' + apGr.GroupDesc + '' | Group: '' + apGr.GroupName GroupFull ,
abc = STUFF
(
(
SELECT '','' + appGrMn.AdministratorMail
FROM APP_GroupManager As appGrMn
-- You only want to combine rows for a single ID here:
WHERE appGrMn.GroupId = apGr.GroupId
FOR XML PATH (''''), TYPE
).value(''.'', ''varchar(max)'')
, 1, 1, '''') ' +
'FROM App_Group apGr ' +
'JOIN T_SensitiveLevel AS tSen ON tSen.SensitiveLevelId = apGr.SensitiveLevelId ' + #WhereQuery +''
PRINT #Query
EXEC(#Query)

Error in my stored procedure in SQL Server

I try to write stored procedure which will check:
If table and columns exists then we write data
If table not exist then we create it and write data
If table exist then we check existing columns and we write data into exists
columns
This is the code:
CREATE PROCEDURE [dbo].[my_proc] #file_path VARCHAR(1000) = NULL
,#file_type VARCHAR(1000) = NULL
,#file_name VARCHAR(1000) = NULL
,#table_name VARCHAR(1000)
AS
BEGIN
DECLARE #sql NVARCHAR(4000);
SET #table_name = '[dbo].[' + #table_name + ']'
SET #sql = '
DECLARE #msg VARCHAR(max)
--if column and table exist
IF (
EXISTS (
SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(''' + #table_name + ''', ''U'')
) --табличка
AND EXISTS (
SELECT *
FROM sys.columns
WHERE object_id = OBJECT_ID(''' + #table_name + ''', ''U'')
AND (
NAME = '' path_file ''
AND NAME = '' file_type ''
AND NAME = '' file_name ''
)
)
) --поля
BEGIN
INSERT INTO ' + #table_name + ' (
file_path
,file_type
,file_name
)
VALUES (
''' + isnull(#file_path, '') + '''
,''' + isnull(#file_type, '') + '''
,''' + isnull(#f ile_name, '') + '''
)
END
--if table not exist
IF NOT EXISTS (
SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(''' + #table_name + ''', ''U'')
)
BEGIN
CREATE TABLE ' + #table_name + ' (
id INT NOT NULL identity(1, 1) PRIMARY KEY
,file_path TEXT
,file_name TEXT
,file_type TEXT
)
END
--if table exist
IF EXISTS (
SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(''' + #table_name + ''', ''U'')
)
BEGIN
--check for columns in table
--file_path
IF NOT EXISTS (
SELECT *
FROM sys.columns
WHERE object_id = OBJECT_ID(''' + #table_name + ''', ''U'')
AND (
NAME = ''path_file''
OR NAME = ''file_path''
)
)
BEGIN
PRINT (''NOT COLUMN path_file'')
END
--file name
IF NOT EXISTS (
SELECT *
FROM sys.columns
WHERE object_id = OBJECT_ID(''' + #table_name + ''', '' U '')
AND NAME = '' file_name ''
)
BEGIN
PRINT ('' NOT COLUMN file_name '')
END
--file_type
IF NOT EXISTS (
SELECT *
FROM sys.columns
WHERE object_id = OBJECT_ID(''' + #table_name + ''', ''U'')
AND (
NAME = ''file_type''
OR NAME = ''file_type''
)
)
BEGIN
PRINT (''NOT COLUMN file_type'')
END
ELSE
INSERT INTO ' + #table_name + ' (
file_path
,file_name
,file_type
)
VALUES (
''' + isnull(#file_path, '') + '''
,''' + isnull(#file_name, '') + '''
,''' + isnull(#f ile_type, '') + '''
)
END';
EXEC (#sql);
END
Trouble with already existing table, but without columns I need
Help me please
I tried to run your script and the only error was happening was a miss declared variable.
You were writing "#f ile_name" with an empty space.
BTW I would suggest you to split your code to read. I tried to mess as little as possible.
CREATE PROCEDURE [dbo].[my_proc]
#file_path VARCHAR(1000) = NULL
,#file_type VARCHAR(1000) = NULL
,#file_name VARCHAR(1000) = NULL
,#table_name VARCHAR(1000)
AS
BEGIN
DECLARE #sql NVARCHAR(4000);
DECLARE #msg VARCHAR(max);
SET #table_name = '[dbo].[' + #table_name + ']'
SET #sql = '
--If table not exist then we create it
IF NOT EXISTS (
SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(N''' + #table_name + ''')
AND type IN (N''U'')
)
BEGIN
CREATE TABLE ' + #table_name + ' (
id INT NOT NULL identity(1, 1) PRIMARY KEY
,file_path TEXT
,file_name TEXT
,file_type TEXT
)
END';
EXEC (#sql);
SET #sql = '
--If table exist then we check existing columns and we write data into exists columns
IF EXISTS (
SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(''' + #table_name + ''', ''U'')
)
BEGIN
PRINT (''TABLE found'')
--check for columns in table
--file_path
IF NOT EXISTS (
SELECT *
FROM sys.columns
WHERE object_id = OBJECT_ID(''' + #table_name + ''', '' U '')
AND (
NAME = '' path_file ''
OR NAME = ''file_path''
)
)
BEGIN
PRINT (''NOT COLUMN path_file'')
END
--file name
IF NOT EXISTS (
SELECT *
FROM sys.columns
WHERE object_id = OBJECT_ID(''' + #table_name + ''', ''U'')
AND NAME = ''file_name''
)
BEGIN
PRINT (''NOT COLUMN file_name'')
END
--file_type
IF NOT EXISTS (
SELECT *
FROM sys.columns
WHERE object_id = OBJECT_ID(''' + #table_name + ''', ''U'')
AND (
NAME = ''file_type''
OR NAME = ''file_type''
)
)
BEGIN
PRINT (''NOT COLUMN file_type'')
END
ELSE
INSERT INTO ' + #table_name + ' (
file_path
,file_name
,file_type
)
VALUES (
''' + isnull(#file_path, '') + '''
,''' + isnull(#file_name, '') + '''
,''' + isnull(#file_type, '') + '''
)
END';
EXEC (#sql);
SET #sql = '
--If table and columns exists then we write data
IF (
EXISTS (
SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(''' + #table_name + ''', ''U'')
) --табличка
AND EXISTS (
SELECT *
FROM sys.columns
WHERE object_id = OBJECT_ID(''' + #table_name + ''', ''U'')
AND (
NAME = ''path_file''
AND NAME = ''file_type''
AND NAME = ''file_name''
)
)
) --поля
BEGIN
INSERT INTO ' + #table_name + ' (
file_path
,file_type
,file_name
)
VALUES (
''' + isnull(#file_path, '') + '''
,''' + isnull(#file_type, '') + '''
,''' + isnull(#file_name, '') + '''
)
END';
EXEC (#sql);
END

How to copy, replace, and insert across all rows in the database

I'll do my best to explain:
Copy all rows that exist in current database
Mass replace a specific string value in every row that contains a specific field
Insert the copied rows
Not sure what approach to take other than hammering out sql scripts.
Thanks!
Is this as simple as creating an Data Flow Source, selecting all the rows, then passing them to a Derived Column transformation, which would be along the lines of:
REPLACE( [ColumnName], "SpecificValue", "ReplacementValue" )
and then insert these rows into your destination table using the relevant Data Flow Destination.
I may be misunderstanding or simplifying step 2...
Assuming you have a table called "table2" and that table consists of the columns facilabbr, unitname, and sortnum... You can select all rows into a temporary table (# signifies a temporary table) changing the "unitname" column to something else...You'll be left with the new values in the temporary table. You can then replace the values in your initial table if you want.
INSERT INTO #temptable1
SELECT facilabbr,
'myNewUnitName' as unitname,
sortnum
FROM table2
DELETE FROM table2
INSERT INTO table2
SELECT facilabbr,
unitname,
sortnum
FROM #temptable1
--THIS QUERY IS ONLY EQUIPPED TO HANDLE:
--SIMPLE NUMERICS SUCH AS FLOATS, INTS, ETC
--SIMPLE STRING DATA TYPES LIMITED TO: VARCHARS, CHARS, NCHARS AND NVARCHARS
--DATES AND DATETIMES
Create Procedure SQLCloner
#TableName as VarChar(max), -- Table that holds data to clone.
#NewTableName as VarChar(max) = '', -- Table to Insert into. If same as Tablename leave blank or write ''.
#VarCharFind as VarChar(max) = '', -- Value to find (In order to replace). If you aren't replacing leave blank or write ''.
#VarCharReplace as VarChar(max) = '', -- Value to replace. If you aren't replacing leave blank or write ''.
#OptionalParam As VarChar(Max) = '' -- Your WHERE clause. If you have none leave blank or write ''.
AS
Declare #index as int = 1
Declare #rowcount As Int = 0
Declare #execFunction As VarChar(max) = ''
Declare #InsertTableRowName As VarChar(max) = ''
Declare #TempFilterType As VarChar(Max) = ''
--Create RowCount of Table
Select #ROWCOUNT = Count(*)
From (
Select Column_Name
From INFORMATION_SCHEMA.COLUMNS
Where Table_Name = '' + #TableName + ''
) As TheCount
--Use While Loop to create Table Columns
While #index <= #rowcount
Begin
--Determines the Variable type to change the exec function accordingly
Select #TempFilterType = TypeTable.DATA_TYPE
From (
Select Data_Type,
ROW_NUMBER() OVER (Order By Ordinal_Position) as RowNum
From INFORMATION_SCHEMA.COLUMNS
Where Table_Name = #TableName
) As TypeTable
Where TypeTable.RowNum = #index
--Prepares #InsertTableRowName With the first part of the string
Set #InsertTableRowName = Case
When #TempFilterType IN('varchar', 'nvarchar','char', 'nchar')
Then #InsertTableRowName + ''''''''' + '
When #TempFilterType IN('datetime', 'date')
Then #InsertTableRowName + ''''''''' + Convert(varchar(Max), '
Else
#InsertTableRowName + 'Convert(varchar(Max), '
End
--Determines the Name of the Column
Select #InsertTableRowName = #InsertTableRowName +
Case
When #TempFilterType IN('varchar', 'nvarchar','char', 'nchar')
Then 'ISNULL(' + 'Replace(' + Column_Name + ','''''''','''''''''''')' + ','''')'
When #TempFilterType IN('datetime', 'date')
Then 'ISNULL(' + 'Replace(' + Column_Name + ','''''''','''''''''''')' + ',''12/31/9999'')'
Else
'ISNULL(' + 'Replace(' + Column_Name + ','''''''','''''''''''')' + ',0)'
End
From (
Select Column_Name,
ROW_NUMBER() OVER (Order By Ordinal_Position) As RowNum
From INFORMATION_SCHEMA.COLUMNS
Where Table_Name = #TableName
) As TheRow
Where RowNum = #index
--Finishes Closes each column insert (in every instance)
Set #InsertTableRowName = Case
When #TempFilterType IN('varchar', 'nvarchar','char', 'nchar')
Then #InsertTableRowName + ' + '''''''''
When #TempFilterType IN('datetime', 'date')
Then #InsertTableRowName + ') + '''''''''
Else
#InsertTableRowName + ') '
End
--Links each Row together with commas and plus signs until the very end.
If #index < #rowcount
Begin
Set #InsertTableRowName = Case
When #TempFilterType IN('varchar', 'nvarchar','char', 'nchar')
Then #InsertTableRowName + ' + ' + ''',''' + ' + '
When #TempFilterType IN('datetime', 'date')
Then #InsertTableRowName + ' + '','' + '
Else
#InsertTableRowName + ' + '','' + '
End
End
Set #index = #index + 1
End
--Puts the Query together (without any of the Parameters yet).
--First, determine if a new table should be used instead.
If #NewTableName = ''
Begin
Set #NewTableName = #TableName
End
--Next, Build the Query, and do it accordingly with if there is a Find/Replace asked for.
Set #execFunction = 'Select '
If #VarCharFind <> ''
Begin
Set #execFunction = #execFunction + 'Replace('
End
Set #execFunction = #execFunction + '''insert into ' + #NewTableName + ' Values('' + ' + #InsertTableRowName + ' + '')'' '
If #VarCharFind <> ''
Begin
Set #execFunction = #execFunction + ', ''' + #VarCharFind + ''', ''' + #VarCharReplace + ''') '
End
Set #execFunction = #execFunction + 'From ' + #TableName
--Adds in the optional Parameters
If #OptionalParam <> ''
Begin
Set #execFunction = #execFunction + ' ' + #OptionalParam
End
Set #execFunction = #execFunction + CHAR(13)+CHAR(10)
--Executes the function and pulls an entire set of queries to copy into the new Database
Print #execFunction
Exec(#execFunction)
GO

How do I script my table to generate INSERT INTO commands?

I have a lookup table with about 10 records, I know I can script the structure to a text file, but how can I script the data to insert into commands?
Ten records, and it's urgent?
Just type it out manually. Should be pretty easy to cut-n-paste.
Assuming SQL Server...
SQL Management Studio will generate an insert script. Right-click your database and select Tasks-Export data
This depends pretty much on the tools you are using...
The quick and dirty way is to run a select into a string and tell sql enterprise manager to give you text (not grid) as the output
SELECT 'INSERT INTO TABLES (fields here) VALUES (' + field1 + ', '....
Do something like this:
select "insert into my_targ_table(my_field_1, my_field_2, ..., my_field_n) values(" || x.my_field_1_col || ", " || x.my_field_2_col || ");"
from my_source_table x
Then just run the script you've generated.
This code works with all tables
DECLARE #TblName varchar(128)
DECLARE #WhereClause varchar(255)
DECLARE #cmd1 varchar(7000)
DECLARE #cmd2 varchar(7000)
SET #TblName = '<tablename>' --Name of your table
SET #WhereClause = ' ' --where clause ex columnA = 1
SET #cmd1 = 'SELECT '' INSERT INTO ' + #TblName + ' ( '
SET #cmd2 = ' + '' VALUES ( '' + '
create table #tableDef (id int identity (1,1), ColType int, ColName varchar(128))
--Fetch column names and datatypes
insert #tableDef (ColType, ColName)
select case when DATA_TYPE like '%char%' then 1
when DATA_TYPE like '%datetime%' then 2
else 0 end ,
COLUMN_NAME
from information_schema.columns
where TABLE_NAME = #TblName
order by ORDINAL_POSITION
SELECT #cmd1 = #cmd1 + ColName + ',',
#cmd2 = #cmd2
+ ' CASE WHEN ' + ColName + ' IS NULL '
+ ' THEN ''NULL'' '
+ ' ELSE '
+ case ColType
when 1 then ''''''''' + ' + ColName + ' + '''''''''
when 2 then ''''''''' + ' + 'CONVERT(VARCHAR(20),' + ColName + ')' + ' + '''''''''
else 'CONVERT(VARCHAR(20),' + ColName + ')' end
+ ' END + '','' + '
from #tableDef
order by id
select #cmd1 = left(#cmd1,len(#cmd1)-1) + ' ) '' '
select #cmd2 = left(#cmd2,len(#cmd2)-8) + '+'')'' FROM ' + #tblName + #WhereClause
select '/*' + #cmd1 + #cmd2 + '*/'
exec (#cmd1 + #cmd2)
drop table #tableDef