0

Working on a project that requires a procedure with a dynamic table name. Need to work out how to write an insert value query into the table. Not a massive project so overheads and such is not an issue.

Tried several variations however it always falls over.

DECLARE @DynamicTableName NVARCHAR(100)
SET @DynamicTableName = 'DynamicTableName'


    INSERT @DynamicTableName
    (
        HolidayStartDate
      , HolidayEndDate
      , HolidayType
      , HolidayTypeID
      , StaffCode
      , StaffName
      , Notes
      , FTE
      , CreatedBy
      , CreatedDate
      , HolidayRequestID
    )
    VALUES
    (       @Para1,
            @Para2,
            @Para3,
            @Para4,
            @Para5,
            @Para5,
            @Para6,
            @Para7,  
            @Para8,
            @Para9, 
            @Para10
    )
1
  • 2
    Not gonna work, an object identifier may not be referenced via a variable. Construct the SQL within a string and call sp_executeSQL, this supports input parameters. Commented Nov 29, 2016 at 13:04

2 Answers 2

1

You can drop the Para1-n into a #Temp table and then perform a dynamic insert.

The benefit here is that you don't have parse or quote parameters

DECLARE @DynamicTableName NVARCHAR(100)
SET @DynamicTableName = 'DynamicTableName'

Select  P1=@Para1,P2=@Para2,P3=@Para3,P4=@Para4,P5=@Para5,P6=@Para6,P7=@Para7,P8=@Para8,P9=@Para9,P10=@Para10 Into TempInsert 
Declare @SQL varchar(max) = '
Insert Into '+@DynamicTableName +'(
        HolidayStartDate
      , HolidayEndDate
      , HolidayType
      , HolidayTypeID
      , StaffCode
      , StaffName
      , Notes
      , FTE
      , CreatedBy
      , CreatedDate
      , HolidayRequestID
    ) Select * From #TempInsert'
Exec(@SQL)

EDIT - I should note that I see only 10 parameters yet you have 11 fields.

Sign up to request clarification or add additional context in comments.

Comments

0
DECLARE @TableName NVARCHAR(100),@QueryStr NVARCHAR(MAX) = ''

SET @QueryStr = 'INSERT INTO ' +@TableName+ '(     
HolidayStartDate,HolidayEndDate,HolidayType, HolidayTypeID, StaffCode
, StaffName, Notes, FTE, CreatedBy, CreatedDate, HolidayRequestID)
VALUES ('+ @Para1 +','+ @Para2 +','+ @Para3 +','+ @Para4 +','+ @Para5 +','+  
@Para5 +','+ @Para6 +','+ @Para7 +','+ @Para8 +','+ @Para9 +','+ @Para10 +')'

 EXEC (@QueryStr)

1 Comment

sp_executeSQL is a better choice as it will escape text within the variables if they are treated as parameters, EXEC() can lead to injection vulnerabilities.

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.