0

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

6
  • Why are you using dynamic SQL? It doesn't seem necessary. Commented Jan 15, 2019 at 18:14
  • I have to have some dynamic variables inside the query. Over here I was just trying to simplify the question. Commented Jan 15, 2019 at 18:15
  • 2
    whats the output of the string if you were to PRINT @SQL? Commented Jan 15, 2019 at 18:20
  • 1
    Very good idea..I found the issue..The replace function was supposed to have instead of ' ' '' '' in the end. Thank you so much. Commented Jan 15, 2019 at 18:23
  • 1
    BOOM! the number 1 piece of advice for debugging dynamic sql is to review the print statement often. Commented Jan 15, 2019 at 18:25

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

Comments

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.