Skyeu
Skyeu

Reputation: 13

Using foreach loop container to create new columns in a table- can't solve "incorrect syntax near '@P1'" error

I'm trying to use a foreach loop container to take row values and make them into fields. But for some reason I can't get it to work without running into this error:

alter table /databasename/.dbo.cp_hh_foo..." failed with the following error: "Incorrect syntax near '@P1'.

The problem appears to be in the final execute SQL statement. The first two execute SQL statements work fine. I think I've made a mistake in my variable/parameter mappings, but I'm not sure.

My data flow looks like this: data flow

Basically what's going on is this:

  1. First Execute SQL Task creates the new table

  2. Second Execute SQL Task selects a table with full result set going into an object-type variable "AllocItems"

general

result set

variables pane

  1. Foreach Loop container (configured as an ADO enumerator) maps specific row from "AllocItems" onto variable "AllocItemsSQL1". These are the strings which should become field names in the table I'm creating

collection

variable mappings

  1. Execute SQL Task within foreach loop container alters the table. The SQL query: alter table MIT_Client_Profitability.dbo.cp_hh_footprint add ? varchar(255)

parameter mapping

Things I've tried:

Thanks in advance for any suggestions!

Upvotes: 1

Views: 427

Answers (2)

billinkc
billinkc

Reputation: 61269

To build on David's answer

Create a new SSIS variable, @[User::Sql] of type String and in the Expression box, add the following syntax

"alter table MIT_Client_Profitability.dbo.cp_hh_footprint add " + @[User::AllocItemSQL1] + " varchar(255);"

The nice thing about this approach is that you can put a breakpoint on the Execute SQL Task and see what the statement looks like prior to the task attempting to execute it. And then modify the Execute SQL Task to use the new variable and remove the parameter.

Otherwise, the dynamic tsql approach ought to have worked, just you needed to modify the syntax. The token replacement won't work inside the string. Something more like this should work according to my mental model

declare @newcolumn varchar(255) = ?;
declare @SQL varchar(255) = 'alter table MIT_Client_Profitability.dbo.cp_hh_footprint add ' + @newcolumn + '  varchar(255)'; 
exec(@SQL);

Upvotes: 2

David Browne - Microsoft
David Browne - Microsoft

Reputation: 89419

This

alter table MIT_Client_Profitability.dbo.cp_hh_footprint add ? varchar(255)

is a Data Definition Language (DDL) statement. DDL cannot be paramterized. You'll have to create the statement with string concatenation.

Upvotes: 1

Related Questions