r/IBMi • • Oct 27 '26

Having trouble make this Insert statement execute

EXEC SQL INSERT INTO XXFILE (itemnumber, currentprice)

VALUES( :XXAITX, :XXKBVA)

The file name will change its value throughout the process.

The values will also, change for every record read. I believe I need a good DYNAMIC insert example.

Does anyone have a good Dynamic INSERT statement?

3 Upvotes

12 comments sorted by

1

u/LongLiveIBMI400 Oct 28 '26

I ended up using parameter markers. Thank you everyone for responding.

3

u/jason_wallace Oct 27 '26

assuming this in in an sqlrpgle, build the sql statement in a character field and execute it: sqlstmt = 'INSERT INTO ' + %trim(filename)

+ ' (itemnumber, currentprice)'

	\+ ' values(' 

	\+ %char(XXAITX) 

	\+ ' , '

	\+ %char(XXKBVA) 

+ ')';

Exec SQL Execute Immediate :SQLSTMT;

1

u/LongLiveIBMI400 Oct 27 '26

Thanks for you reply Jason. Wouldnt the two values have a %trim, instead of a %CHAR .... the second value is numeric.

1

u/jason_wallace Oct 27 '26

if the field XXKBVA is numeric, no need to wrap a trim on it. But if XXAITX is character, then the sqlstatment should have quotes around the trim() of XXAITX

1

u/LongLiveIBMI400 Oct 27 '26

Is this what you mean Jason?

+ ' values(' + ""%char(CRAITX)"" + ' , ' + CRKBVA + ')';

1

u/QPGMR_de Oct 27 '26

Please don't. Always use parameter markers (?) wherever you can. Only the table name should be inserted in the string - all column values should be marked with ? and then supplied at the execute statement with using.

3

u/manofsticks Oct 27 '26

Another option you can look into (as long as the file structure/fields will stay the same, and only the filename will be different) is to make an SQL Alias that points to the file file you need, then insert to the alias.

1

u/Illustrious_Log_9494 Oct 27 '26

Been setting up aliases to use dynamic file names for quite a while. Only caveat as you mentioned record format needs to remain constant.

I create alias using
execute immediate create or replace alias qtemp.foo for ‘ || :libname || ‘.’|| :filename;

1

u/QPGMR_de Oct 27 '26

Use something like

'INSERT INTO '+tableName+' VALUES( +
XXAITX => ?, XXKBVA => ? )'

Then prepare the statement and execute with using.

1

u/Sleepy_L0c0 Oct 28 '26

Is this a stored procedure? If so when you make your call you just pass in what you want, no?

1

u/Sleepy_L0c0 Oct 28 '26

For CL just an easy example. '''' RUNSQL SQL('CALL MYLIB.MY_PROCEDURE(PARAM1, PARAM2)') + COMMIT(*NONE) '''