Reputation: 64
I am using the below query to insert data from one table to another:
DECLARE @MATNO NVARCHAR(10), @GLOBALREV INT, @LOCALREP INT
SET @MATNO = '7AGME'
SET @GLOBALREV = 11
SET @LOCALREP = 1
INSERT INTO CIGARETTE_HEADER
VALUES
(SELECT *
FROM CIGARETTE_HEADER_BK1
WHERE MATERIAL_NUMBER = @MATNO
AND GLOBAL_REVISION = @GLOBALREV
AND LOCAL_REVISION = @LOCALREP)
The column in both the tables are same, but I am getting the following error:
Msg 156, Level 15, State 1, Line 7
Incorrect syntax near the keyword 'SELECT'.Msg 102, Level 15, State 1, Line 7
Incorrect syntax near ')'.
Can you please let me know the mistake here?
Upvotes: 0
Views: 6756
Reputation: 194
To expand a bit on the issue.
VALUES() is actually a table constructor. When inserting rows into a table you can either use SELECT to fetch rows or VALUE constructor.
Even though INSERT INTO... VALUES is often used in examples to insert a row, you can use it to insert multiple rows, separating them with commas.
Eg. INSERT INTO table(col1, col2) VALUES (1, 2) , (3, 4) , (5, 6)
Would insert a set of 3 rows into your table.
VALUES can also be used to make derived tables, allowing some advanced data manipulation.
https://msdn.microsoft.com/en-us/library/dd776382.aspx
Upvotes: 1
Reputation: 82
You don't need to use the VALUES () notation. You only use this when you want to insert static values, and only one register. Example: INSERT INTO Table VALUES('value1',12, newid());
Also i recommend writing the name of the columns you plan to insert into, like this:
INSERT INTO Table
(String1, Number1, id)
VALUES('value1',12, newid());
In your case, do the same but only with the select:
DECLARE @MATNO NVARCHAR(10), @GLOBALREV INT, @LOCALREP INT;
SET @MATNO = '7AGME';
SET @GLOBALREV = 11;
SET @LOCALREP = 1;
INSERT INTO CIGARETTE_HEADER
(ColumnName1, ColumnName2)
SELECT ColumnNameInTable1, ColumnNameInTable2
FROM CIGARETTE_HEADER_BK1
WHERE MATERIAL_NUMBER = @MATNO
AND GLOBAL_REVISION = @GLOBALREV
AND LOCAL_REVISION = @LOCALREP);
Upvotes: 2
Reputation: 72165
You don't need VALUES
keyword:
INSERT INTO CIGARETTE_HEADER
SELECT * FROM CIGARETTE_HEADER_BK1
WHERE MATERIAL_NUMBER = @MATNO AND
GLOBAL_REVISION = @GLOBALREV AND
LOCAL_REVISION = @LOCALREP
It is also preferable to explicitly cite every field name of both tables participating in the INSERT
statement.
Upvotes: 6