1

I'm struggling to get this statement run

SET @SelectStatement = 'INSERT INTO [ArchiveProcessHistory] VALUES (' + @TableName + ',' + @TotalRowsSource +',' + @TotalRowsDestination + ',' + GetDate()') '

[I know something is wrong with the above statment, which I'm not able to fix)

SET @FullStatement = @SelectStatement 

ArchiveProcessHistory Table Structure is:

TableName - nvarch(5)
TotalRowsSource - integer
TotalRowsDestination - integer
DateofInsert - Date

It's giving me this error when i run through sp_executesql

Msg 102, Level 15, State 1, Procedure usp_ArchiveTable, Line 39 Incorrect syntax near ') '.

How can I solve this?

3 Answers 3

1
SET @SelectStatement = 'INSERT INTO [ArchiveProcessHistory] VALUES (' + @TableName + ',' + @TotalRowsSource +',' + @TotalRowsDestination + ',' + GetDate() + ') '

Missing one + after getdate().

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

Comments

1

To avoid a potential SQL Injection attack you could use sp_executesql instead.

declare @SelectStatement nvarchar(max)

set @SelectStatement = 
  'INSERT INTO [ArchiveProcessHistory] VALUES
    (@TableName, @TotalRowsSource, @TotalRowsDestination, GetDate())'

exec sp_executesql @SelectStatement,
                   N'@TableName nvarchar(5), @TotalRowsSource int, @TotalRowsDestination int',
                   @TableName = '123', 
                   @TotalRowsSource = 4, 
                   @TotalRowsDestination = 5

You should also have a look at The Curse and Blessings of Dynamic SQL

3 Comments

+1 - if dynamic SQL is truly required (not clear from the question if there is any need for it), use parameterised SQL like this
But these are @TableName are input parameters which are passed to stored procredure.
@ConradJagger You don't use it as a table name in your query. If you do, you should concatenate the table name into @SelectStatement using quotename().
0

Instead of GetDate() in your insert statement which is a function, use current_timestamp.

SET @SelectStatement = 'INSERT INTO [ArchiveProcessHistory] VALUES (' + @TableName + ','   + @TotalRowsSource +',' + @TotalRowsDestination + ',' + current_timestamp + ') '

1 Comment

This is failing because TableName is VARCHAR ... and above statement fails when I run it... varchar error

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.