简体   繁体   中英

Inserting data in temp table in dynamic query

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

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;

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