Inserting data in temp table in dynamic query

时间:2019-01-15 18:12:07

标签: sql sql-server sql-server-2012

I have this query

declare @SQL  as NVARCHAR(MAX);

create table #TempCalcPerc
( 
    PctAPAC nvarchar(50),
    PctEMEA nvarchar(50),
    PctLAmerica nvarchar(50),
    PctNAmerica nvarchar(50)
)

set @SQL = 'Insert into 
#TempCalcPerc(PctAPAC,PctEMEA,PctLAmerica,PctNAmerica)
select RTrim(LTrim(Replace([rRecurringMarginPct-Apac],''%'',''))),
RTrim(LTrim(Replace([rRecurringMarginPct-Emea],''%'',''))),
RTrim(LTrim(Replace([rRecurringMarginPct-LatinAmerica],''%'',''))),
RTrim(LTrim(Replace([rRecurringMarginPct-NorthAmerica],''%'','')))
from DashboardData
where DataType = ''SLPayroll'''

exec sp_executeSQL @SQL;

I am basically just trying to insert some data into a temp table after some replace operation.

Although I have 4 columns selected in the select query, I get this error:

The select list for the INSERT statement contains fewer items than the insert list. The number of SELECT values must match the number of INSERT columns.

If I execute the SQL normally without it being dynamic the query runs fine. Can someone please have a look and let me know what I am doing wrong here.

Also if I change the query to be the insert seems to work fine.

set @SQL = 'Insert into 
    #TempCalcPerc(PctAPAC,PctEMEA,PctLAmerica,PctNAmerica)
    select 1,2,3,4'

exec sp_executeSQL @SQL;

Thanks

1 个答案:

答案 0 :(得分:1)

how about :

Create table #TempCalcPerc
( 
  PctAPAC nvarchar(50),
  PctEMEA nvarchar(50),
  PctLAmerica nvarchar(50),
  PctNAmerica nvarchar(50)
)

declare @SQL  as NVARCHAR(MAX);
SET @SQL = 'Insert into 
#TempCalcPerc(PctAPAC,PctEMEA,PctLAmerica,PctNAmerica)
select RTrim(LTrim(Replace([rRecurringMarginPct-Apac],''%'',''''))),
RTrim(LTrim(Replace([rRecurringMarginPct-Emea],''%'',''''))),
RTrim(LTrim(Replace([rRecurringMarginPct-LatinAmerica],''%'',''''))),
RTrim(LTrim(Replace([rRecurringMarginPct-NorthAmerica],''%'','''')))
from DashboardData
where DataType = ''SLPayroll'''

exec @SQL;