0

New to using SQL and I am having trouble accomplishing something that I figured would be simple.

I am trying to create and INSERT that will insert the MAX() value from the first column in one table to the first column in another table while the rest of the columns will be filled with parameters.

I have tried switching my code around to see if I just had the syntax wrong but I've had no luck and I'm not even sure what I'm trying to do is possible (at least in a single INSERT).

Here is what I have at the moment:

INSERT INTO [Table2] VALUES(SELECT(Number FROM [Table1] WHERE Max(Number)), @p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9, @p10)
1
  • try creating the script in Sql Server Management Studio (SSMS) first and then work it into your code. Commented Apr 6, 2011 at 14:04

2 Answers 2

1

the select statement must be enclosed in parentheses and I recommend you always put the list of columns in the insert statement

Insert into [MyTable] (Max,Value1,Value2,Value3) values((select Max(Number) from Table1),@p1,@p2,@p3)
Sign up to request clarification or add additional context in comments.

1 Comment

Ahh, damn parentheses. Thanks for your help, this worked perfectly.
0

First: The SELECT MAX statement is wrong, the correct syntax is:

SELECT Max(Number) From [Table1]

Second: the INSERT syntax is wrong. To use a subquery you have to select values for every field in the destination table, while if you use the VALUES keyword you have to specify the field to insert the value in.

So your query have to became something like this:

INSERT INTO [Table2] 
SELECT Max(Number), @p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9, @p10 From [Table1]

OR (i'm using lesser parameter for practical reason)

INSERT INTO [Table2] (field1,field2,field3)
VALUES
(@MAX, @p1, @p2)

where @MAX is a variable containing the result of

SELECT Max(Number) From [Table1]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.