An INSERT statement cannot contain a SELECT statement that assigns values to a variable.

Error Message:
Msg 199, Level 15, State 1, Line 0
An INSERT statement cannot contain a SELECT statement that assigns values to a variable.

Severity level:
15.

Description:
This error message appears when you try to use an INSERT statement that contains a SELECT statement, in which values are assigned to a variable.

Consequences:
The SQL statement cannot be parsed and further execution is stopped.

Resolution:
Error of the Severity level 15 are generated by the user and can be fixed by the SQL Server user. The statement cannot be executed this way. You cannot assign values to a variable in an INSERT statement that uses a SELECT statement.

Versions:
All versions of SQL Server.

Example(s):
USE tempdb;
GO
IF OBJECT_ID(‘tempdb..#t’) > 0
 DROP TABLE #t
GO
CREATE TABLE #t
(
 id INT
);
GO
DECLARE @i INT
INSERT INTO #t SELECT @i = 1;
SELECT *
  FROM #t
 GROUP BY 1

Remarks:
In the above example we try to assign a value to the variable @i in the SELECT part of the above INSERT statement. This raises the error.

]]>

Leave a comment

Your email address will not be published.