I'm trying to create a procedure to create multiple tables at once, either using a while or another command.
This is the database I have to create, but I was wondering if there was a faster way to do it through a loop:
The creation of column fields or fields in tables are the same. The problem arises when naming the tables created, since there are several.
declare #i int = 1
while (#i <= 11)
begin
declare #nameoftable nvarchar(50)
set #nameoftable ='dbo'+ '.' + 'tbl_' + convert(nvarchar, #i) + '000_Capitulo_100'
print #nameoftable
create table #nameoftable
(
cap100ID int primary key not null,
ccdd int not null,
ccpp int not null,
ccdi int not null,
tipoVia nvarchar(20) not null,
nombVia nvarchar(50) not null
)
set #i = #i + 1
end;
This is the code that I advanced so far in sql server management.
Got to agree with the comments regarding having multiple tables with identical structure and the possible problems it could cause but if you really need to do this you could use EXEC.
declare #i int = 1
while (#i <= 11)
begin
declare #nameoftable nvarchar(50)
declare #sqlCommand nvarchar(255)
set #nameoftable ='dbo'+ '.' + 'tbl_' + convert(nvarchar, #i) + '000_Capitulo_100'
SET #sqlCommand = 'create table ' + #nameoftable +
'(cap100ID int primary key not null,
ccdd int not null,
ccpp int not null,
ccdi int not null,
tipoVia nvarchar(20) not null,
nombVia nvarchar(50) not null)'
EXEC (#sqlCommand)
set #i = #i + 1
end;
not sure , this is what your are looking for?
EXEC('create table '+#nameoftable+'
(
cap100ID int primary key not null,
ccdd int not null,
ccpp int not null,
ccdi int not null,
tipoVia nvarchar(20) not null,
nombVia nvarchar(50) not null
)')
Related
I have two stored procedures, one calling the other.Though there is no error at compilation in any of them, but on running SearchProcedure, the outputprocedure is not called from with in. I see no reason it not being called. SearchProcedure has been working fine so far.
Please direct what might be the issue.
I know OutputProcedureis not being called as I tried using Select statements in it.
Here is the code:
Calling as follows:
Exec SearchProcedure #firstname ='Simran', #middlename='kaur', #lastname = 'Khurana', #City='Delhi'
Procedures:
CREATE Procedure OutputProcedure
(
#LastNameFromUser nvarchar(20) = null,
#LastNameFromTable nvarchar(20),
#MiddleNameFromUser nvarchar(20) = null,
#MiddleNameFromTable nvarchar(20) = null,
#CityFromUser nvarchar(20) = null,
#CityFromTable nvarchar(20) = null,
#Percentage int out
)
AS
BEGIN
select 'OUTPUTPROCEDURECALLED'
declare #maxvalue int
DECLARE #variableTable TABLE (
idx int identity(1,1),
matchvalue nvarchar(15))
INSERT INTO #variableTable(matchvalue) values ('MiddleName')
INSERT INTO #variableTable(matchvalue) values ('LastName')
INSERT INTO #variableTable(matchvalue) values ('City')
SELECT * FROM #variableTable
DECLARE #counter int
declare #sql nvarchar(100)
declare #sql2 nvarchar(25), #finalResult nvarchar(100)
declare #sql3 nvarchar(300), #tempresultStore nvarchar(20), #temp int, #temp2 int, #average int
SET #counter = 1
SELECT #maxvalue = (SELECT MAX(idx) FROM #variableTable)
select #maxvalue as 'MAXVALUE'
WHILE(#counter <= #maxvalue)
BEGIN
DECLARE #colVar nvarchar(15)
SELECT #colVar = matchvalue FROM #variableTable WHERE idx = #counter
set #sql = 'declare' +' ' + '#Temp'+ #colVar
exec #sql
select #sql as 'SQLFORDECLARATIONS'
set #temp = CHARINDEX(' ',#sql)
select #temp as 'resultofcharindex'
set #temp2 = #temp + 1
SELECT #temp2 AS 'AFTERADDING1'
set #tempresultStore = Right(#sql, #temp2)
SELECT #tempresultStore AS 'FINALCUTPART'
set #sql3 = 'SET ' + #sql2 + '= set ' + ' ' + #tempresultStore + '=' + 'dbo.[Match' + #colVar + '](' + #colVar + 'FromUser' + ',' + #colVar + 'FromTable' + ',' + 0 + ')'
EXEC #sql3
select #sql3 as 'check sql query formed'
set #finalResult = #finalResult + #sql2
select #finalResult as 'SUM'
SET #counter = #counter + 1
select #counter as 'COUNTERVALUE'
END
set #Percentage = #finalResult/#maxvalue
SELECT #Percentage AS 'FINALRESULT'
RETURN
END
create procedure SearchProcedure
(
#firstname nvarchar(20),
#middlename nvarchar(20) = null,
#lastname nvarchar(20),
#DOB Date = null,
#SSN nvarchar(30)= null,
#ZIP nvarchar(10)= null,
#StateOfResidence nvarchar(2)= null,
#City nvarchar(20)= null,
#StreetName nvarchar(20)= null,
#StreetType nvarchar(20)= null,
#BuildingNumber int= null,
#Aptnumber nvarchar(10)= null
)
As
DECLARE #sSQL NVARCHAR(2000), #Where NVARCHAR(1000) = ' '
declare #Percent int,
#FN nvarchar(20),
#MN nvarchar(20) = null,
#LN nvarchar(20),
#DateOfB Date = null,
#SSNumber nvarchar(30)= null,
#ZIPCode nvarchar(10)= null,
#StateOfRes nvarchar(2)= null,
#CityOfRes nvarchar(20)= null,
#StreetNameRes nvarchar(20)= null,
#StreetTypeRes nvarchar(20)= null,
#BuildingNumberRes int= null,
#AptnumberRes nvarchar(10)= null
set #Percent = 0
create table #results
(
firstname nvarchar(20) not null,
middlename nvarchar(20),
lastname nvarchar(20)not null,
PercentageMatch int not null,
DOB Date,
SSN nvarchar(30),
ZIP nvarchar(10),
[State] nvarchar(2),
City nvarchar(20),
StreetName nvarchar(20),
StreetType nvarchar(20),
BuildingNumber int,
Aptnumber nvarchar(10)
)
declare c Cursor local static Read_only
for
SELECT * from dbo.Patients where firstname = #FN
open c
fetch next from c into #FN,
#MN,
#LN,
#DateOfB,
#SSNumber,
#ZIPCode,
#StateOfRes,
#CityOfRes,
#StreetNameRes,
#StreetTypeRes,
#BuildingNumberRes,
#AptnumberRes
while ##FETCH_STATUS = 0 BEGIN
/*set #Percent = dbo.[MatchLastName](#lastname, #LN, #Percent)
set #Percent = dbo.[MatchMiddleName](#middlename, #MN, #Percent)
set #Percent = dbo.[MatchCity](#City, #CityOfRes, #Percent)*/
Exec [dbo].[OutputProcedure] #lastname, #LN, #middlename, #MN,#City, #CityOfRes, #Percent output
Insert into #results values
(#FN,#MN,#LN,#Percent, #DateOfB,#SSNumber, #ZIPCode,#StateOfRes,#CityOfRes,#StreetNameRes,#StreetTypeRes,#BuildingNumberRes,#AptnumberRes)
fetch next from c into #FN,
#MN,
#LN,
#DateOfB,
#SSNumber,
#ZIPCode,
#StateOfRes,
#CityOfRes,
#StreetNameRes,
#StreetTypeRes,
#BuildingNumberRes,
#AptnumberRes
end
select * from #results order by PercentageMatch desc
IF OBJECT_ID('tempdb..#results') IS NOT NULL DROP TABLE #results
go
In SearchProcedure is there code missing that sets variable fn; you open your cursor with
declare c Cursor local static Read_only
for
SELECT * from dbo.Patients where firstname = #FN
only i don't see where #fn is set; if the cursor has no rows then the second procedure won't get called as the loop won't run.
By using the dynamic SQL, I created a variable name like this:
set #tempresultStore = 'Temp'+#colVar
Now, #tempresultstore has the value 'TempMiddleName', then I declared this variable named TempMiddleName and assigned the value in the same line in dynamic sql query and executed.
The code is as follows :(Scroll down to code line with comment to follow where the problem is)
CREATE Procedure OutputProcedure
#LastNameFromUser nvarchar(20) = null,
#LastNameFromTable nvarchar(20),
#MiddleNameFromUser nvarchar(20) = null,
#MiddleNameFromTable nvarchar(20) = null,
#CityFromUser nvarchar(20) = null,
#CityFromTable nvarchar(20) = null,
#Percentage int out
AS
BEGIN
SELECT #MiddleNameFromTable AS'middlename'
select #LastNameFromTable as 'LASTNAMEFROMTABLE'
select #LastNameFromUser as 'LASTNAMEFROMUser'
select 'OUTPUTPROCEDURECALLED'
declare #maxvalue int , #finalpercentage int = 0
DECLARE #variableTable TABLE
(
idx int identity(1,1),
matchvalue nvarchar(15)
)
INSERT INTO #variableTable(matchvalue) values ('MiddleName')
INSERT INTO #variableTable(matchvalue) values ('LastName')
INSERT INTO #variableTable(matchvalue) values ('City')
SELECT * FROM #variableTable
DECLARE #counter int
declare #sql nvarchar(100)
declare #sql2 nvarchar(25), #finalResult nvarchar(100)
set #finalResult = 0;
declare #sql3 nvarchar(300), #sql4 nvarchar(15), #tempresultStore nvarchar(20), #temp int, #temp2 int, #average int
DECLARE #ParmeterDefinition nvarchar(500);
set #ParmeterDefinition =
N'#LastNameFromUsnvarchar(20),
#LastNameFromTab nvarchar(20),
#MiddleNameFromUs nvarchar(20),
#MiddleNameFromTab nvarchar(20),
#CityFromUs nvarchar(20),
#CityFromTab nvarchar(20),
#Percent int out'
SET #counter = 1
SELECT #maxvalue = (SELECT MAX(idx) FROM #variableTable)
select #maxvalue as 'MAXVALUE'
WHILE(#counter < #maxvalue)
BEGIN
DECLARE #colVar nvarchar(15)
SELECT #colVar = matchvalue FROM #variableTable WHERE idx = #counter
set #tempresultStore = 'Temp'+#colVar --here
SELECT #tempresultStore AS 'FINALCUTPART'
select 'JUSTBEFORSQL'
set #sql3 = 'declare #Temp' + #colVar + ' int = dbo.[Match' + #colVar + '](' + #colVar + 'FromUser,' + #colVar + 'FromTable, 0)'
select #sql3 as 'check sql query formed'
EXEC sp_executesql #sql3,
#ParmeterDefinition,
#LastNameFromUs = #LastNameFromUser,
#LastNameFromTab = #LastNameFromTable,
#MiddleNameFromUs = #MiddleNameFromUser,
#MiddleNameFromTab = #MiddleNameFromTable,
#CityFromUs = #CityFromUser,
#CityFromTab = #CityFromTable,
#Percent = #Percentage out
select #Percentage AS 'PERCENTRETRIVED'
set #finalResult = #finalResult + #Percentage /*here #Percentage always remains 0. It is the value returned by the UDF called by the dynamic SQL above.The function does return the value but probably I fail to store it correctly.*/
select #finalResult as 'SUM'
SET #counter = #counter + 1
select #counter as 'COUNTERVALUE'
END
set #finalpercentage = #finalResult/#maxvalue
SELECT #finalpercentage AS 'FINALRESULT'
RETURN
END
Go
How do I access the int value stored in variable called #TempMIddleName
It should work with output keyword. No need for creating table. I don't know but your code is not correct. You have output parameter #Percent and assign value of function to #TempMiddleName, then you should have not a #Percent as Output but #TempMiddleName.
You get dynamic SQL
declare #TempMiddleName int = dbo.[MatchMiddleName](MiddleNameFromUser,MiddleNameFromTable, 0)
I had answered you once, that you miss # before your variables.
Also you have provided variable #Percent(and others as well) for dynamic query, but you don't assign any value to it. Try changing
SET #sql3 = 'declare #Temp' + #colVar + ' int = dbo.[Match' + #colVar + '](' + #colVar + 'FromUser,' + #colVar + 'FromTable, 0)'
to
SET #sql3 = 'select #Percent = 1'
and you will see that 1 is returned as supposed to.
Also you have error here. Split first parameter from its type
set #ParmeterDefinition =
N'#LastNameFromUsnvarchar(20),
set #ParmeterDefinition =
N'#LastNameFromUs nvarchar(20),
You would need to dynamically create a temporary table, and access it's value by selecting the top 1 value from it. Something like the following;
CREATE TABLE #ResultValue (Value Varchar(200))
DECLARE #DynamicSql NVarchar(MAX) = ''
SELECT #DynamicSql = '
DECLARE #tempresultStore Varchar(50)
DECLARE #colVar Varchar(50) = ''MiddleName''
SET #tempresultStore = ''Temp'' + #colVar
insert into #ResultValue
select #tempresultStore
'
EXEC sp_sqlexec #DynamicSql
SELECT * FROM #ResultValue
DROP TABLE #ResultValue
If you paste all your code we might try to amend it for you.
I would like have a generic procedure to Update my look Up Table.
CREATE TYPE S_Reference.[ReferenceType] as TABLE (
[Id] SMALLINT NOT NULL PRIMARY KEY,
[Code] VARCHAR(16) UNIQUE NOT NULL,
[Rank] SMALLINT NOT NULL CHECK([Rank]>0),
[Description] VARCHAR(128) NOT NULL,
[Base] BIT NOT NULL DEFAULT 0);
GO
CREATE PROCEDURE [S_Reference].[P_B_ReferenceMerge]
#Values [ReferenceType] READONLY,
#TableName NVARCHAR(50)
AS
DECLARE #SQLQuery NVARCHAR(200)
SET #SQLQuery = 'SELECT * FROM ' + #TableName
MERGE INTO #SQLQuery Ori
USING
#Values New
ON (Ori.[Id] = New.[Id])
WHEN MATCHED THEN
UPDATE
SET Ori.[Code] = New.[Code],
Ori.[Rank] = New.[Rank],
Ori.[Description] = New.[Description],
Ori.[Base] = New.[Base]
WHEN NOT MATCHED THEN
INSERT (Ori.[Id] , Ori.[Code], Ori.[Rank],Ori.[Description] ,Ori.[Base])
Values (New.[Id] , New.[Code], New.[Rank],New.[Description] ,New.[Base]);
RETURN 0
But I don't know how to use the "tableName" ?
I get an error on Ori.[Id], I think the problem comes from
SET #SQLQuery = 'SELECT * FROM ' + #TableName
MERGE INTO #SQLQuery Ori
If can help this is how I did. By this way You can manage easily the values in your look up (reference or enum in c#).
First the procedure:
CREATE TYPE S_Reference.[ReferenceType] AS TABLE (
[Id] SMALLINT NOT NULL PRIMARY KEY,
[Code] VARCHAR(40) UNIQUE NOT NULL,
[Rank] SMALLINT UNIQUE NOT NULL CHECK([Rank]>0),
[Description] VARCHAR(128) NOT NULL,
[Base] BIT NOT NULL DEFAULT 0);
GO
CREATE PROCEDURE [S_Reference].[P_M_ReferenceMerge]
#Values S_Reference.[ReferenceType] READONLY,
#TableName NVARCHAR(50)
AS
CREATE TABLE #NewValues (
[Id] SMALLINT NOT NULL PRIMARY KEY,
[Code] VARCHAR(40) UNIQUE NOT NULL,
[Rank] SMALLINT UNIQUE NOT NULL CHECK([Rank]>0),
[Description] VARCHAR(128) NOT NULL,
[Base] BIT NOT NULL DEFAULT 0);
Insert INTO #NewValues
select * From #Values
DECLARE #SQLQuery NVARCHAR(MAX)
SET #SQLQuery =
'DELETE
FROM ' + #TableName + '
WHERE [Id] IN (SELECT [Id]
FROM ' + #TableName + '
EXCEPT
SELECT [Id]
FROM #NewValues)
MERGE INTO ' + #TableName + ' Ori
USING #NewValues New
ON (Ori.[Id] = New.[Id])
WHEN MATCHED THEN
UPDATE
SET Ori.[Code] = New.[Code],
Ori.[Rank] = New.[Rank],
Ori.[Description] = New.[Description],
Ori.[Base] = New.[Base]
WHEN NOT MATCHED THEN
INSERT ([Id] , [Code], [Rank], [Description] ,[Base])
Values (New.[Id] , New.[Code], New.[Rank], New.[Description] ,New.[Base]);'
EXEC sp_executesql #SQLQuery
RETURN 0
Usage
INSERT INTO
#VALUES([Id],[Code],[Rank],[Description] ,[Base])
Values
(1,'EUR',1,'EUR',0),
(2,'GBP',2,'GBP',0),
(3,'USD',3,'USD',0)
EXEC [S_Reference].[P_M_ReferenceMerge]
#Values = #VALUES,
#TableName = 'S_Reference.T_R_Currency'
DELETE FROM #VALUES
I want to use Dynamic SQL within a stored procedure to create a table.
Here is the call to the stored procedure:
EXEC [spCreateAColDiffTable] 'hq193.dbo.arch_con_col_s193_s202'
Here are the relevant parts of the stored procedure:
CREATE PROCEDURE sp_createAColDiffTable (#table_name nvarchar(128))
...
SET #sSQL = 'CREATE TABLE ' + #table_name + ' ( ' +
' [table_name] VARCHAR (128) NOT NULL, ' +
' [column_name] VARCHAR (128) NULL, ' +
' [what_changed] VARCHAR (128) NULL, ' +
' [sr_data_type] VARCHAR (128) NOT NULL, ' +
' [tr_data_type] VARCHAR (128) NOT NULL, ' +
' [sr_max_length] SMALLINT NOT NULL, ' +
' [tr_max_length] SMALLINT NOT NULL, ' +
' [sr_is_nullable] CHAR NULL, ' +
' [tr_is_nullable] CHAR NULL, ' +
' [sr_precision] SMALLINT NULL, ' +
' [tr_precision] SMALLINT NULL, ' +
' [sr_scale] SMALLINT NULL, ' +
' [tr_scale] SMALLINT NULL ) ' +
' ON [PRIMARY] WITH (DATA_COMPRESSION = NONE)'
PRINT #sSQL
Exec #sSQL
GO
When I run the stored procedure I receive the error:
SQL Server Database Error: The name 'CREATE TABLE
hq193.dbo.arch_con_col_s193_s202 ( [table_name] VARCHAR (128) NOT
NULL, [column_name] VARCHAR (128) NULL, [what_changed] VARCHAR (128)
NULL, [sr_data_type] VARCHAR (128) NOT NULL, [tr_data_type] VARCHAR
(128) NOT NULL, [sr_max_length] SMALLINT NOT NULL, [tr_max_length]
SMALLINT NOT NULL, [sr_is_nullable] CHAR NULL, [tr_is_nullable] CHAR
NULL, [sr_precision] SMALLINT NULL, [tr_precision] SMALLINT NULL,
[sr_scale] SMALLINT NULL, [tr_scale] SMALLINT NULL ) ON [PRIMARY] WITH
(DATA_COMPRESSION = NONE)'
is not a valid identifier.
Notice in the stored procedure I printed out the SQL before I executed it. If I cut and paste the SQL that gets printed into a query editor window it works fine.
What am I missing?
Try it like this:
EXEC(#sSQL)
This is a very common error. Without the parenthesis, EXEC #sSQL means "execute a stored procedure whose name is in the #sSQL variable", rather than what you want which is probably "Execute the command string in the variable #sSQL."
I see this is an old post, but I've had a similar issue where I need to read a text file where the columns may of changed by having more and less depending on how the file was pulled. So I wrote a program to read the text file and put it into a dynamically created temp table where I can work with the output.
Perhaps this can help someone else..
DECLARE #NUM_COL AS INT
DECLARE #I AS INT
DECLARE #CREATE_TBL AS NVARCHAR(MAX)
DECLARE #DATA AS NVARCHAR (MAX)
DECLARE #XML_ROW AS XML
DECLARE #MAX_CHAR AS INT
--Sets the column max characters for temp table ##FILE_TABLE
SET #MAX_CHAR = 1000
--File import of data as single rows, no columns
IF OBJECT_ID('tempdb..#FILE_ROWS') IS NOT NULL
DROP TABLE #FILE_ROWS
CREATE TABLE #FILE_ROWS
( [Row_data] NVARCHAR(MAX) NULL )
--Global temp table used because the table is being built dynamically.
IF OBJECT_ID('tempdb..##FILE_TABLE') IS NOT NULL
DROP TABLE ##FILE_TABLE
--This is only so the debugger thinks the table is created when referenced in later SQL code.
IF 1 <> 1 CREATE TABLE ##FILE_TABLE (X INT)
BULK INSERT #FILE_ROWS
FROM 'C:\Users\Wayne\Desktop\777434633016764.txt'
WITH
(
FIELDTERMINATOR = '\t' --Tab Delimited
,ROWTERMINATOR = '\n'
)
--Figures out how many columns were in the file.
SET #NUM_COL = (SELECT MAX(LEN(Row_data) - LEN(REPLACE(Row_data, CHAR(9), ''))) + 1 AS [NO_COL] FROM #FILE_ROWS)
SET #CREATE_TBL = 'CREATE TABLE ##FILE_TABLE ( ID INT IDENTITY(1,1),'
SET #I = 1
Declare COUNTER Cursor for
SELECT
CAST('<A>' + REPLACE(Row_data, CHAR(9), '</A><A>') + '</A>' AS XML)
FROM #FILE_ROWS
open COUNTER
fetch next from COUNTER into #XML_ROW
while ##fetch_Status != -1
begin
IF #I = 1
BEGIN
SELECT #CREATE_TBL = #CREATE_TBL
+ '[' + REPLACE(dbo.Trim(DATA.value('.','char(30)')), N'''', '`')
+ ']' + ' NVARCHAR(' + CAST(#MAX_CHAR AS NVARCHAR(5)) + ') NULL,'
FROM #XML_ROW.nodes('/A') AS x(DATA)
SET #CREATE_TBL = LEFT(#CREATE_TBL, LEN(#CREATE_TBL) - 1) + ')'
EXEC(#CREATE_TBL)
SET #I = 2
END
--ELSE --If you do not want the column names in the first row, remove the ELSE
BEGIN
SET #DATA = 'INSERT INTO ##FILE_TABLE SELECT '
SELECT #DATA = #DATA
+ '''' + REPLACE(dbo.Trim(DATA.value('.','char(30)')), N'''', '`')
+ '''' + ','
FROM #XML_ROW.nodes('/A') AS x(DATA)
SET #DATA = LEFT(#DATA, LEN(#DATA) -1)
EXEC(#DATA)
END
FETCH NEXT FROM COUNTER INTO #XML_ROW
END
CLOSE COUNTER
DEALLOCATE COUNTER
SELECT * from ##FILE_TABLE
I'm trying to set IDENTITY seed parameter while creating table, getting it from a var. Something like this
DECLARE #MaxID INTEGER
SET #MaxID = (SELECT TOP 1 ID FROM dbo.ProductQuotes ORDER BY ID DESC) + 1;
CREATE TABLE [dbo].[Z](
[ID] int PRIMARY KEY not null IDENTITY(#MaxID,1),
[Number] int NULL,
[Name] nvarchar(50) COLLATE Cyrillic_General_CI_AS NULL
) ON [PRIMARY]
GO
Error is "incorrect syntax near '#MaxID' (in this row [ID] int PRIMARY KEY not null IDENTITY(#MaxID,1) )
But I'm not sure it's about syntax at all. Can somebody explain me where am I wrong here? :)
This cannot be parameterised.
You would need to use dynamic SQL as below.
DECLARE #MaxID INTEGER
SELECT #MaxID = 1 + ISNULL(MAX(ID),0) FROM dbo.ProductQuotes
DECLARE #Script NVARCHAR(MAX) =
N'
CREATE TABLE [dbo].[Z](
[ID] int PRIMARY KEY not null IDENTITY(' + CAST(#MaxID AS NVARCHAR(10)) + ',1),
[Number] int NULL,
[Name] nvarchar(50) COLLATE Cyrillic_General_CI_AS NULL
) ON [PRIMARY]
'
EXEC (#Script);
I assume you will take precautions to ensure that ProductQuotes cannot be subject to any inserts during the import process.
Something like
DECLARE #MaxID INTEGER
DECLARE #SQL varChar(4000)
SET #MaxID = (SELECT TOP 1 ID FROM dbo.ProductQuotes ORDER BY ID DESC) + 1;
Set #SQL = 'CREATE TABLE [dbo].[Z]([ID] int PRIMARY KEY not null IDENTITY(' +
Convert(VarChar(8),#MaxID) +
',1), [Number] int NULL, [Name] nvarchar(50) COLLATE Cyrillic_General_CI_AS NULL) ON [PRIMARY]
Exec(#sql)
Build the sql statement using the teh value of #MaxID then execute it.