简体   繁体   中英

Dynamically built sql server insert statement fails to insert

We dynamically build a sql statement after validation

After running some code the generated values for the insert looks like this:

(1, 1, SYSDATETIME(), null),
(4, 1, SYSDATETIME(), null),
(6, 1, SYSDATETIME(), null),
(8, 1, SYSDATETIME(), null)

Valid SQL Syntax

We then user this as follows

IF(@Activities != null)
Begin
 INSERT INTO [User].[User_Activities]
       (UserId, ActivitieId, DateCreated, DateDeleted)
 VALUES
       @Activities
END

@Activities being the above dynamically built SQL statement, its throws an error saying incorrect syntax by @Activities.

Even though in SQL query window it looks like this:

Insert into [User].User_Activities
(UserId, ActivitieId, DateCreated, DateDeleted)
Values
(1, 1, SYSDATETIME(), null),
(4, 1, SYSDATETIME(), null),
(6, 1, SYSDATETIME(), null),
(8, 1, SYSDATETIME(), null)

and executes successfully, how can I make this work successfully via the application?

Take a look at either SqlBulkCopy or table-valued-parameters. These offer a much cleaner way to insert multiple records into a SQL database from a C# app.

Using @Activities like this does not build a dynamic SQL statement. It combines a static part of a statement with a dynamic one, which is not possible in SQL Server.

You also have to correctly formulate the IF statement: != operator cannot be used for inequality comparison against NULL value (it will never evaluate to TRUE ). IS NOT NULL is used in this case.

You have to use EXEC to achieve what you want:

IF(@Activities IS NOT NULL)
BEGIN
  EXEC('INSERT INTO [User].[User_Activities]
          (UserId, ActivitieId, DateCreated, DateDeleted)
        VALUES' + @Activities)
END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM