Hi! I need some expert advise.
This is what I am trying to do:
1. I have two tables Table1 and Table2 in the same db.
2. Table2 has one column more than Table1. The extra column is the primary
key.
3. Copy contents of Table1 => Table2 but also add the extra primary key value
which is a sequential number.
Questions:
1. Is stored procedure the best way to do this ?
2. I do need to be sure Table1 does have data. So, should I do the following ?
IF ((Select count(*) from Table1) > 0)
do something .... what is the syntax of IF Statements in SPROC ?
3. Do I have to read a table row at a time ? Is CURSOR the best way to do
it ?
Any help or code snipets will be appreciated.
I am using .NET with SQL 2000 and C# on a windows platform.
Thanks,
LWI think you will just need an INSERT statement:
INSERT INTO Table2 (col1, col2, ...)
SELECT col1, col2, ...
FROM Table1
--
David Portas
SQL Server MVP
--|||The following will not work for me because:
1. Table2 has one extra column so when do I insert it ?
2. Also, how do I go through all records in Table1 ?
LW
"David Portas" wrote:
> I think you will just need an INSERT statement:
> INSERT INTO Table2 (col1, col2, ...)
> SELECT col1, col2, ...
> FROM Table1
> --
> David Portas
> SQL Server MVP
> --
>
>|||1. You said that the extra column is a sequential number. If you make that
an IDENTITY column then the number will be assigned automatically - you
don't need to generate it. Lookup IDENTITY in Books Online. Note that
IDENTITY does not enforce any uniqueness constraint on your data. IDENTITY
is therefore no substitute for having a meaningful unique key in your table.
2. The SELECT statement will select ALL rows from Table1 unless you specify
a WHERE clause. You don't need to loop through each one. This is why SQL
statements are called "set operations" - because they work on SETS of rows,
not individual records.
--
David Portas
SQL Server MVP
--|||David,
Thanks very much. I read up on IDENTITY and it will work really well
for my table.
The stored procedure is working just as you said. Amazing how simple
it was.
LW
"David Portas" wrote:
> 1. You said that the extra column is a sequential number. If you make that
> an IDENTITY column then the number will be assigned automatically - you
> don't need to generate it. Lookup IDENTITY in Books Online. Note that
> IDENTITY does not enforce any uniqueness constraint on your data. IDENTITY
> is therefore no substitute for having a meaningful unique key in your table.
> 2. The SELECT statement will select ALL rows from Table1 unless you specify
> a WHERE clause. You don't need to loop through each one. This is why SQL
> statements are called "set operations" - because they work on SETS of rows,
> not individual records.
> --
> David Portas
> SQL Server MVP
> --
>
>
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment