I'm putting together a statement INSERT
in SQL with values stored in variables that come from a CURSOR
that I'm looping through. At the time of executing the instruction INSERT
I am getting an invalid identifier error.
The code I'm working on is the following and it's inside a repeating loop that gets data from a cursor:
IF (@Estado = 'V')
SET @NuevoEstado = 'ACT'
ELSE
SET @NuevoEstado = 'ANU'
SET @ClienteId = (
SELECT ClienteId
FROM QueryClientesDescriptivo
WHERE CodigoContribuyente = @RUC
AND Estado = 'ACT'
)
SET @MovimientoInventarioId = @MovimientoInventarioId + 1
SET @Query = 'INSERT INTO [COMPU90].[SIV3].[dbo].MovimientosInventario (CompaniaId, MovimientoInventarioId, TipoMovimientoInventarioId, Fecha, Glosa, AlmacenId, PersonaId, Estado, OrigenId, Migracion) ' + 'VALUES (' + CHAR(39) + '10043' + CHAR(39) + ',' + CHAR(39) + CONVERT(VARCHAR, @MovimientoInventarioId) + CHAR(39) + ',' + CHAR(39) + 'SVEN' + CHAR(39) + ',' + CHAR(39) + CONVERT(VARCHAR, @Fecha, 101) + CHAR(39) + ',' + CHAR(39) + '' + CHAR(39) + ',' + CHAR(39) + '2' + CHAR(39) + ',' + CHAR(39) + CONVERT(VARCHAR, @ClienteId) + CHAR(39) + ',' + CHAR(39) + @NuevoEstado + CHAR(39) + ',' + CHAR(39) + '0' + CHAR(39) + ',' + CHAR(39) + '0' + CHAR(39) + ')'
EXEC @Query
The error message I get is the following:
The name 'INSERT INTO [COMPU90].[SIV3].[dbo].MovementsInventory (CompanyId, MovementInventoryId, TypeMovementInventoryId, Date, Gloss, WarehouseId, PersonId, Status, OriginId, Migration) VALUES ('10043','141907',' SVEN','01/04/2016','','2','253624','ANU','0','0')' is not a valid identifier.
I have tried changing the format of the date, the way in which to pass the parameters but no way frees me from that error, however, when executing it directly it works without giving me errors.
Add parentheses, on the line that executes the query:
You could also launch the query using the stored procedure
sp_executesql
that I mentioned in your other questionThe code you would use would be the following (in my example I make a loop to insert 10 records):
The advantage of doing it this way is that the code is much cleaner and more maintainable and that the parameters are typed.
And probably more optimal because, being a parameterized query, there will be a single execution plan