inserting the max colum in the stored proc

I

iHavAQuestion

I have stored procedure
Create Stored Procedure Name
(
@Var1
@Var2
@Var3
)
Inseret into table1
(
Col1
col2
col3
)
Values
(
@Var1
@Var2
@Var3
)

But in col1 i need to insert select max(col) from tablename, which is in the
same database.

how do I do that??
 
G

George Ter-Saakov

you can use something like in (MS SQL)

INSERT INTO table1(Col1, Col2,Col3)
SELECT MAX(col1), col2, col3 GROUP BY col2, col3




George
 
B

bruce barker

Inseret into table1 (
col1
col2
col3
)
Values (
(select max(col1) from table1
@Var2
@Var3
)

of course if two inserts happen at the same time, they will get the same
result. you can set the isolation level to serializable (at a big performance
cost), or if col1 has a unique index, catch the duplicate key error and
resubmit on the failed insert (a better option)

a better option is to use the identity constaint, at let sqlserver assign
the max.

-- bruce (sqlwork.com)
 
I

iHavAQuestion

Thats fine...
But, I actually wanted to add the MAX(col) from tabe that exists from the
same data base in place of @var1/Col1 in the below stored procedure

Hope you got my question

Create Stored Procedure Name
(
@Var1
@Var2
@Var3
)
Inseret into table1
(
Col1
col2
col3
)
Values
(
@Var1
@Var2
@Var3
)
 
I

iHavAQuestion

Thats fine...
But, I actually wanted to add the MAX(col) from tabe that exists from the
same data base in place of @var1/Col1 in the below stored procedure

Hope you got my question

Create Stored Procedure Name
(
@Var1
@Var2
@Var3
)
Inseret into table1
(
Col1
col2
col3
)
Values
(
@Var1
@Var2
@Var3
)
 
G

George Ter-Saakov

Sorry, completely not clear....
Can you rephrase or may be write what you want in pseudo SQL....

PS: I meant to say
INSERT INTO table1(Col1, Col2,Col3)
SELECT MAX(col1), col2, col3 FROM table1 GROUP BY col2, col3


George.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top