How to store multiple SQLExec values in variable(s) - peoplesoft

I am wondering whether in an Application Engine PeopleCode I can run a SQLExec command and if multiple rows are returned how they are stored in the variable?
For example - I am working on adding the following code:
SQLExec("SELECT C.UNIT_OF_MEASURE FROM PS_ITM_VNDR_UOM_PR C WHERE C.INV_ITEM_ID = :1 AND C.VENDOR_ID = :2 AND C.EFFDT = (SELECT MAX(C1.EFFDT) FROM PS_ITM_VNDR_UOM_PR C1 WHERE C.SETID = C1.SETID AND C.INV_ITEM_ID = C1.INV_ITEM_ID AND C.VENDOR_SETID = C1.VENDOR_SETID AND C.VENDOR_ID = C1.VENDOR_ID AND C.VNDR_LOC = C1.VNDR_LOC AND C.UNIT_OF_MEASURE = C1.UNIT_OF_MEASURE AND C.CURRENCY_CD = C1.CURRENCY_CD AND C.QTY_MIN = C1.QTY_MIN)" , &InvItemId, &VendorID, &UOMResult
In certain cases more than one row (value) may be passed back into the &UOMResult variable from the SQL query and I am not sure how PeopleCode will handle this, but ultimately I want to compare the value(s) from the &UOMResult variable to another variable called &UOM and if they are different (don't have a match) then do certain "stuff", else do "other stuff".
Does the variable get transformed into an array if there is more than 1 value returned from the SQL? Just wondering what this would look like... Thanks for any feedback you have.
10/17/18 EDIT:
Local SQL &SQL;
Local string &VendorId, &InvItemId, &ItmIdVndr, &UOM, &ConvRate, &PriceVndr, &Oprid, &PriceStatus, &VendorId_check, &insert_cols, &insert_select, &insert_where, &insert_sql, &Error, &MaxEffdt, &ItmField;
Local date &Effdt;
Local Record &ITM_VNDR_UOM_PR, &REC, &MASTER_ITEM_TBL;
&Oprid = "'BATCH'";
&PriceStatus = "2";
&Error = "N";
MessageBox(0, "", 0, 0, "**** BEGINING OF VALIDATION ERRORS ****");
&SQL = CreateSQL("SELECT VENDOR_ID, INV_ITEM_ID, ITM_ID_VNDR, UNIT_OF_MEASURE, CONVERSION_RATE, PRICE_VNDR, %DateOut(EFFDT), ITEM_FIELD_C10_B FROM PS_GH_ITM_PR_UPDT ORDER BY VENDOR_ID, INV_ITEM_ID, ITM_ID_VNDR", &VendorId, &InvItemId, &ItmIdVndr, &UOM, &ConvRate, &PriceVndr, &Effdt, &ItmField);
MessageBox(0, "", 0, 0, &VendorId | " " | &InvItemId | " " | &ItmIdVndr | " " | &UOM | " " | &ConvRate | " " | &PriceVndr | " " | &Effdt | " " | &ItmField | " " | &Error);
While &SQL.Fetch(&VendorId, &InvItemId, &ItmIdVndr, &UOM, &ConvRate, &PriceVndr, &Effdt, &ItmField)
SQLExec("SELECT A.VENDOR_ID FROM PS_ITM_VENDOR A, PS_ITM_VNDR_UOM B WHERE A.SETID = B.SETID AND A.INV_ITEM_ID = B.INV_ITEM_ID AND A.VENDOR_SETID = B.VENDOR_SETID AND A.VENDOR_ID = B.VENDOR_ID AND A.VENDOR_ID = :1 AND A.INV_ITEM_ID = :2 AND A.ITM_ID_VNDR = :3 AND A.ITM_VNDR_PRIORITY = 1 AND B.UNIT_OF_MEASURE = :4 AND B.CONVERSION_RATE = :5", &VendorId, &InvItemId, &ItmIdVndr, &UOM, &ConvRate, &VendorId_check);
If None(&VendorId_check) Then;
&Error = "Y";
MessageBox(0, "", 0, 0, &VendorId | " " | &InvItemId | " " | &ItmIdVndr | " " | &UOM | " " | &ConvRate | " " | &PriceVndr | " " | &Effdt | " " | &ItmField | " " | &Error);
Else;
&CurrentDateTime = %Datetime;
&Oprid = %OperatorId;
&RECITEM = CreateRecord(Record.ITM_VNDR_UOM_PR);
/*CHC Modification - Denise Smith - 8/8/2012 - CHC_PO_96588 - Begin */
/*SQLExec("SELECT TO_CHAR(C.EFFDT,'DD-MON-YYYY') FROM PS_ITM_VNDR_UOM_PR C WHERE C.INV_ITEM_ID = :1 AND C.VENDOR_ID = :2 AND C.UNIT_OF_MEASURE = :3 AND C.EFFDT = (SELECT MAX(C1.EFFDT) FROM PS_ITM_VNDR_UOM_PR C1 WHERE C.SETID = C1.SETID AND C.INV_ITEM_ID = C1.INV_ITEM_ID AND C.VENDOR_SETID = C1.VENDOR_SETID AND C.VENDOR_ID = C1.VENDOR_ID AND C.VNDR_LOC = C1.VNDR_LOC AND C.UNIT_OF_MEASURE = C1.UNIT_OF_MEASURE AND C.CURRENCY_CD = C1.CURRENCY_CD AND C.QTY_MIN = C1.QTY_MIN) ", &InvItemId, &VendorId, &UOM, &MaxEffdt);*/
/*GETTING MAX EFFECTIVE DATED ROW TO COPY EXISTING ROW VALUES FROM INTO NEW ROW */
SQLExec("SELECT C.EFFDT FROM PS_ITM_VNDR_UOM_PR C WHERE C.INV_ITEM_ID = :1 AND C.VENDOR_ID = :2 AND C.UNIT_OF_MEASURE = :3 AND C.EFFDT = (SELECT MAX(C1.EFFDT) FROM PS_ITM_VNDR_UOM_PR C1 WHERE C.SETID = C1.SETID AND C.INV_ITEM_ID = C1.INV_ITEM_ID AND C.VENDOR_SETID = C1.VENDOR_SETID AND C.VENDOR_ID = C1.VENDOR_ID AND C.VNDR_LOC = C1.VNDR_LOC AND C.UNIT_OF_MEASURE = C1.UNIT_OF_MEASURE AND C.CURRENCY_CD = C1.CURRENCY_CD AND C.QTY_MIN = C1.QTY_MIN) ", &InvItemId, &VendorId, &UOM, &MaxEffdt);
&SQL2 = CreateSQL("SELECT C.UNIT_OF_MEASURE FROM PS_ITM_VNDR_UOM_PR C WHERE C.INV_ITEM_ID = :1 AND C.VENDOR_ID = :2 AND C.EFFDT = (SELECT MAX(C1.EFFDT) FROM PS_ITM_VNDR_UOM_PR C1 WHERE C.SETID = C1.SETID AND C.INV_ITEM_ID = C1.INV_ITEM_ID AND C.VENDOR_SETID = C1.VENDOR_SETID AND C.VENDOR_ID = C1.VENDOR_ID AND C.VNDR_LOC = C1.VNDR_LOC AND C.UNIT_OF_MEASURE = C1.UNIT_OF_MEASURE AND C.CURRENCY_CD = C1.CURRENCY_CD AND C.QTY_MIN = C1.QTY_MIN) ", &InvItemId, &VendorId);
/* This is where I am afraid the While loop will create extra inserts if the SQL above contains more than 1 Row. That is why I only want to evaluate only once if possible. For example if I am wanting to add a new price with a new UOM -'TP' that does not already exist for this item I want to look at the output value(s) from above &SQL2 and compare to my &UOM variable. If I keep this logic in a While loop I'm afraid it will end up creating more insert's then necessary */
While &SQL2.Fetch(&UOMResult)
If &UOM = &UOMResult Then;
SQLExec("%SelectAll(:1) WHERE INV_ITEM_ID = :2 AND VENDOR_ID = :3 AND UNIT_OF_MEASURE = :4 AND (CONVERT(CHAR(10),EFFDT,121)) = :5", &RECITEM, &InvItemId, &VendorId, &UOM, &MaxEffdt, &RECITEM);
/*SQLExec("%SelectAll(:1) WHERE INV_ITEM_ID = :2 AND VENDOR_ID = :3 AND UNIT_OF_MEASURE = :4 AND EFFDT = :5", &RECITEM, &InvItemId, &VendorId, &UOM, &MaxEffdt, &RECITEM); */
&new_UNIT_OF_MEASURE = &RECITEM.UNIT_OF_MEASURE.Value;
&REC = CreateRecord(Record.ITM_VNDR_UOM_PR);
&REC.SETID.Value = &RECITEM.SETID.Value;
&REC.INV_ITEM_ID.Value = &RECITEM.INV_ITEM_ID.Value;
&REC.VENDOR_SETID.Value = &RECITEM.VENDOR_SETID.Value;
&REC.VENDOR_ID.Value = &RECITEM.VENDOR_ID.Value;
&REC.VNDR_LOC.Value = &RECITEM.VNDR_LOC.Value;
&REC.UNIT_OF_MEASURE.Value = &RECITEM.UNIT_OF_MEASURE.Value;
&REC.CURRENCY_CD.Value = &RECITEM.CURRENCY_CD.Value;
&REC.QTY_MIN.Value = &RECITEM.QTY_MIN.Value;
&REC.EFFDT.Value = &Effdt;
&REC.EFF_STATUS.Value = &RECITEM.EFF_STATUS.Value;
&REC.PRICE_VNDR.Value = &PriceVndr;
&REC.UNIT_PRC_TOL.Value = &RECITEM.UNIT_PRC_TOL.Value;
&REC.EXT_PRC_TOL.Value = &RECITEM.EXT_PRC_TOL.Value;
&REC.PCT_UNIT_PRC_TOL.Value = &RECITEM.PCT_UNIT_PRC_TOL.Value;
&REC.PCT_EXT_PRC_TOL.Value = &RECITEM.PCT_EXT_PRC_TOL.Value;
&REC.USE_STD_TOLERANCES.Value = &RECITEM.USE_STD_TOLERANCES.Value;
&REC.QTY_RECV_TOL_PCT.Value = &RECITEM.QTY_RECV_TOL_PCT.Value;
&REC.UNIT_PRC_TOL_L.Value = &RECITEM.UNIT_PRC_TOL_L.Value;
&REC.PCT_UNIT_PRC_TOL_L.Value = &RECITEM.PCT_UNIT_PRC_TOL_L.Value;
&REC.EXT_PRC_TOL_L.Value = &RECITEM.EXT_PRC_TOL_L.Value;
&REC.PCT_EXT_PRC_TOL_L.Value = &RECITEM.PCT_EXT_PRC_TOL_L.Value;
&REC.BU_PRICE_STATUS.Value = "2";
&REC.STD_PRICE_STATUS.Value = "2";
&REC.LEAD_TIME.Value = &RECITEM.LEAD_TIME.Value;
&REC.OPRID_MODIFIED_BY.Value = &Oprid;
&REC.LAST_DTTM_UPDATE.Value = &CurrentDateTime;
&REC.PRICE_CHANGE.Value = &RECITEM.PRICE_CHANGE.Value;
&REC.Insert();
Else;
SQLExec("%SelectAll(:1) WHERE INV_ITEM_ID = :2 AND VENDOR_ID = :3 AND UNIT_OF_MEASURE = :4 AND (CONVERT(CHAR(10),EFFDT,121)) = :5", &RECITEM, &InvItemId, &VendorId, &UOMResult, &MaxEffdt, &RECITEM);
/*SQLExec("%SelectAll(:1) WHERE INV_ITEM_ID = :2 AND VENDOR_ID = :3 AND UNIT_OF_MEASURE = :4 AND EFFDT = :5", &RECITEM, &InvItemId, &VendorId, &UOMResult, &MaxEffdt, &RECITEM); */
&new_UNIT_OF_MEASURE = &RECITEM.UNIT_OF_MEASURE.Value;
&REC = CreateRecord(Record.ITM_VNDR_UOM_PR);
&REC.SETID.Value = &RECITEM.SETID.Value;
&REC.INV_ITEM_ID.Value = &RECITEM.INV_ITEM_ID.Value;
&REC.VENDOR_SETID.Value = &RECITEM.VENDOR_SETID.Value;
&REC.VENDOR_ID.Value = &RECITEM.VENDOR_ID.Value;
&REC.VNDR_LOC.Value = &RECITEM.VNDR_LOC.Value;
&REC.UNIT_OF_MEASURE.Value = &RECITEM.UNIT_OF_MEASURE.Value;
&REC.CURRENCY_CD.Value = &RECITEM.CURRENCY_CD.Value;
&REC.QTY_MIN.Value = &RECITEM.QTY_MIN.Value;
&REC.EFFDT.Value = &Effdt;
&REC.EFF_STATUS.Value = &RECITEM.EFF_STATUS.Value;
&REC.PRICE_VNDR.Value = &PriceVndr;
&REC.UNIT_PRC_TOL.Value = &RECITEM.UNIT_PRC_TOL.Value;
&REC.EXT_PRC_TOL.Value = &RECITEM.EXT_PRC_TOL.Value;
&REC.PCT_UNIT_PRC_TOL.Value = &RECITEM.PCT_UNIT_PRC_TOL.Value;
&REC.PCT_EXT_PRC_TOL.Value = &RECITEM.PCT_EXT_PRC_TOL.Value;
&REC.USE_STD_TOLERANCES.Value = &RECITEM.USE_STD_TOLERANCES.Value;
&REC.QTY_RECV_TOL_PCT.Value = &RECITEM.QTY_RECV_TOL_PCT.Value;
&REC.UNIT_PRC_TOL_L.Value = &RECITEM.UNIT_PRC_TOL_L.Value;
&REC.PCT_UNIT_PRC_TOL_L.Value = &RECITEM.PCT_UNIT_PRC_TOL_L.Value;
&REC.EXT_PRC_TOL_L.Value = &RECITEM.EXT_PRC_TOL_L.Value;
&REC.PCT_EXT_PRC_TOL_L.Value = &RECITEM.PCT_EXT_PRC_TOL_L.Value;
&REC.BU_PRICE_STATUS.Value = "2";
&REC.STD_PRICE_STATUS.Value = "2";
&REC.LEAD_TIME.Value = &RECITEM.LEAD_TIME.Value;
&REC.OPRID_MODIFIED_BY.Value = &Oprid;
&REC.LAST_DTTM_UPDATE.Value = &CurrentDateTime;
&REC.PRICE_CHANGE.Value = &RECITEM.PRICE_CHANGE.Value;
&REC.Insert();
End-If;
End-While;
End-If;
/* KDR - 10/11/2018 - Added field ITEM_FIELD_C10_B (&ItmField) to CSV file layout and insert into PS_MASTER_ITEM_TBL (&MASTER_ITEM_TBL) */
If None(&ItmField) Then;
&Error = "Y";
MessageBox(0, "", 0, 0, &VendorId | " " | &InvItemId | " " | &ItmIdVndr | " " | &UOM | " " | &ConvRate | " " | &PriceVndr | " " | &Effdt | " " | &ItmField);
Else;
SQLExec("UPDATE PS_MASTER_ITEM_TBL SET ITEM_FIELD_C10_B = :1 WHERE INV_ITEM_ID = :2 AND SETID = 'SHARE' ", &ItmField, &InvItemId);
/* Else;
&REC1 = CreateRecord(Record.MASTER_ITEM_TBL);
&REC1.ITEM_FIELD_C10_B.Value = &ItmField;
&REC1.SETID.Value = "SHARE";
&REC1.INV_ITEM_ID.Value = &InvItemId;
&REC1.Update();
End-If; */
End-If;
End-While;
MessageBox(0, "", 0, 0, "**** END OF VALIDATION ERRORS ****");
MessageBox(0, "", 0, 0, " ");`

SQLExec only ever stores the results of 1 row. If you want to be able to loop through multiple rows returned you need to use a SQL object. Further documentation can be found in the Enterprise PeopleTools PeopleBook: PeopleCode API Reference > SQL Class
Local SQL &sql;
&sql = createsql("SELECT C.UNIT_OF_MEASURE FROM PS_ITM_VNDR_UOM_PR C WHERE C.INV_ITEM_ID = :1 AND C.VENDOR_ID = :2 AND C.EFFDT = (SELECT MAX(C1.EFFDT) FROM PS_ITM_VNDR_UOM_PR C1 WHERE C.SETID = C1.SETID AND C.INV_ITEM_ID = C1.INV_ITEM_ID AND C.VENDOR_SETID = C1.VENDOR_SETID AND C.VENDOR_ID = C1.VENDOR_ID AND C.VNDR_LOC = C1.VNDR_LOC AND C.UNIT_OF_MEASURE = C1.UNIT_OF_MEASURE AND C.CURRENCY_CD = C1.CURRENCY_CD AND C.QTY_MIN = C1.QTY_MIN)",&InvItemId, &VendorID);
while &sql.fetch(&UOMResult)
/* Do you logic here */
end-while;
&sql.close;

When I use App Engine and I have to create 2 or more result sets based on a differing set of criteria, I take 2 approaches:
if can I use case statements in the field select clause to achieve my objective, then this is the preferred method.
write SQLs in multiple steps that are mutually exclusive (from source table perspective) and populate the same target table.
If possible, I will avoid manipulating SQL with PeopleCode because then you have to deal with PeopleCode quirks as well as the database itself.

Related

How can I use last-of in a QUERY-PREPARE()?

I made a huge code and it was taking a very long time to process. Following suggestions here, I made it shorter and better and now it's running much faster. However, I noticed I should be getting a sum of the values whereas I'm just getting the values. I tried using ACCUMULATE TOTAL, but it didn't work because the LAST-OF can only be used with a BREAK BY and my break by is inside the QUERY-PREPARE().
How can I get the sum of the following values?
doc-fiscal.vl-cont-doc
doc-fiscal.vl-bicms
doc-fiscal.vl-icms
doc-fiscal.vl-icmsou
doc-fiscal.vl-ipiou
doc-fiscal.vl-ipi
Bellow is the code I'm using, which is working almost perfectly.
//Query
cQuery = "FOR EACH doc-fiscal WHERE doc-fiscal.dt-docto >= " + QUOTER(pd-data-1) + " AND doc-fiscal.dt-docto <= " + QUOTER(pd-data-2) + " AND (doc-fiscal.cod-observa <> 4 OR doc-fiscal.tipo-nat <> 3) AND doc-fiscal.cd-situacao <> 06 AND doc-fiscal.cd-situacao <> 22".
cQuery = cQuery + semCodEmitente + comCodEmitente + CheckBoxindSitDoc.
cQuery = cQuery + ", EACH natur-oper USE-INDEX natureza WHERE doc-fiscal.nat-operacao = natur-oper.nat-operacao" + modeloEletronico + tipoEntrada + natOper.
cQuery = cQuery + " BREAK BY doc-fiscal.dt-docto BY doc-fiscal.nr-doc-fis ".
QUERY qRelatorio:QUERY-PREPARE(cQuery).
QUERY qRelatorio:QUERY-OPEN().
GET FIRST qRelatorio.
DEF VAR soma-vl-cont-doc AS DECIMAL.
DO WHILE AVAILABLE doc-fiscal:
soma-vl-cont-doc = soma-vl-cont-doc + doc-fiscal.vl-cont-doc.
IF LAST-OF(doc-fiscal.nr-doc-fis) THEN DO:
CREATE tt-relatorio.
ASSIGN
tt-relatorio.nr-doc-fis = doc-fiscal.nr-doc-fis
tt-relatorio.serie = doc-fiscal.serie
tt-relatorio.char-2 = SUBSTRING(doc-fiscal.char-2,155,44, "CHAR")
tt-relatorio.cod-model-nf-eletro = natur-oper.cod-model-nf-eletro
tt-relatorio.tipo = natur-oper.tipo
tt-relatorio.cod-estabel = doc-fiscal.cod-estabel
tt-relatorio.cod-emitente = doc-fiscal.cod-emitente
tt-relatorio.nome-ab-emi = doc-fiscal.nome-ab-emi
tt-relatorio.cgc = doc-fiscal.cgc
tt-relatorio.dt-emis-doc = doc-fiscal.dt-emis-doc
tt-relatorio.dt-docto = doc-fiscal.dt-docto
tt-relatorio.ind-sit-doc = doc-fiscal.ind-sit-doc
tt-relatorio.vl-cont-doc = doc-fiscal.vl-cont-doc
tt-relatorio.vl-bicms = doc-fiscal.vl-bicms
tt-relatorio.vl-icms = doc-fiscal.vl-icms
tt-relatorio.vl-icmsou = doc-fiscal.vl-icmsou
tt-relatorio.vl-ipiou = doc-fiscal.vl-ipiou
tt-relatorio.vl-ipi = doc-fiscal.vl-ipi
tt-relatorio.imp-nota = natur-oper.imp-nota.
GET NEXT qRelatorio.
END.
END.
QUERY qRelatorio:QUERY-CLOSE().
Thanks for the help and sorry for being such a newbie. I hope my question can help other people.
I managed to do it.
I used LAST-OF() METHOD. My code became the following.
DEF VAR soma-vl-cont-doc AS DECIMAL. //INICIO DAS SOMAS
DEF VAR soma-vl-bicms AS DECIMAL.
DEF VAR soma-vl-icms AS DECIMAL.
DEF VAR soma-vl-icmsou AS DECIMAL.
DEF VAR soma-vl-ipiou AS DECIMAL.
DEF VAR soma-vl-ipi AS DECIMAL.
DO WHILE AVAILABLE doc-fiscal:
soma-vl-cont-doc = soma-vl-cont-doc + doc-fiscal.vl-cont-doc.
soma-vl-bicms = soma-vl-bicms + doc-fiscal.vl-bicms.
soma-vl-icms = soma-vl-icms + doc-fiscal.vl-icms.
soma-vl-icmsou = soma-vl-icmsou + doc-fiscal.vl-icmsou.
soma-vl-ipiou = soma-vl-ipiou + doc-fiscal.vl-ipiou.
soma-vl-ipi = soma-vl-ipi + doc-fiscal.vl-ipi.
IF QUERY qRelatorio:LAST-OF(2) THEN DO:
CREATE tt-relatorio.
ASSIGN
tt-relatorio.nr-doc-fis = doc-fiscal.nr-doc-fis
tt-relatorio.serie = doc-fiscal.serie
tt-relatorio.char-2 = SUBSTRING(doc-fiscal.char-2,155,44, "CHAR")
tt-relatorio.cod-model-nf-eletro = natur-oper.cod-model-nf-eletro
tt-relatorio.tipo = natur-oper.tipo
tt-relatorio.cod-estabel = doc-fiscal.cod-estabel
tt-relatorio.cod-emitente = doc-fiscal.cod-emitente
tt-relatorio.nome-ab-emi = doc-fiscal.nome-ab-emi
tt-relatorio.cgc = doc-fiscal.cgc
tt-relatorio.dt-emis-doc = doc-fiscal.dt-emis-doc
tt-relatorio.dt-docto = doc-fiscal.dt-docto
tt-relatorio.ind-sit-doc = doc-fiscal.ind-sit-doc
tt-relatorio.vl-cont-doc = soma-vl-cont-doc
tt-relatorio.vl-bicms = soma-vl-bicms
tt-relatorio.vl-icms = soma-vl-icms
tt-relatorio.vl-icmsou = soma-vl-icmsou
tt-relatorio.vl-ipiou = soma-vl-ipiou
tt-relatorio.vl-ipi = soma-vl-ipi
//tt-relatorio.idi-sit-nf-eletro = nota-fiscal.idi-sit-nf-eletro
tt-relatorio.imp-nota = natur-oper.imp-nota.
soma-vl-cont-doc = 0.
soma-vl-bicms = 0.
soma-vl-icms = 0.
soma-vl-icmsou = 0.
soma-vl-ipiou = 0.
soma-vl-ipi = 0.
END.
GET NEXT qRelatorio.
END.
With this, I managed to get the answers I wanted andthe query is quite fast. If there's any suggestions as to how make it faster, I'm open for them. Thanks.

CreateRecord Update Method does not update table

I have modified the below App Engine program to update a field on an existing row, using a File Layout. I have added code to update existing rows for items that have a new Vendor Item ID populated. While the program doesn’t error while running, it also does not actually update the table PS_ITM_VENDOR with the ITM_ID_VNDR field. The program reads the file layout appropriately, and I can display the variable for ITM_ID_VNDR. I'm not sure I am using the .Update method correctly for the CreateRecord class. The changes are notated by the '1/7/2020' comment at the bottom.
Local SQL &SQL, &SQL2;
Local string &VendorId, &InvItemId, &ItmIdVndr, &UOM, &ConvRate, &PriceVndr, &Oprid, &PriceStatus, &VendorId_check, &insert_cols, &insert_select, &insert_where, &insert_sql, &Error, &MaxEffdt, &ItmIdVndrNew;
Local date &Effdt;
Local Record &ITM_VNDR_UOM_PR, &REC, &REC1;
&Oprid = "'BATCH'";
&PriceStatus = "2";
&Error = "N";
MessageBox(0, "", 0, 0, "**** BEGINING OF VALIDATION ERRORS ****");
&SQL = CreateSQL("SELECT VENDOR_ID, INV_ITEM_ID, ITM_ID_VNDR, UNIT_OF_MEASURE, CONVERSION_RATE, PRICE_VNDR, %DateOut(EFFDT), ITM_ID_VNDR_NEW FROM PS_GH_ITM_PR_UPDT ORDER BY VENDOR_ID, INV_ITEM_ID, ITM_ID_VNDR", &VendorId, &InvItemId, &ItmIdVndr, &UOM, &ConvRate, &PriceVndr, &Effdt, &ItmIdVndrNew);
While &SQL.Fetch(&VendorId, &InvItemId, &ItmIdVndr, &UOM, &ConvRate, &PriceVndr, &Effdt, &ItmIdVndrNew)
SQLExec("SELECT A.VENDOR_ID FROM PS_ITM_VENDOR A, PS_ITM_VNDR_UOM B WHERE A.SETID = B.SETID AND A.INV_ITEM_ID = B.INV_ITEM_ID AND A.VENDOR_SETID = B.VENDOR_SETID AND A.VENDOR_ID = B.VENDOR_ID AND A.VENDOR_ID = :1 AND A.INV_ITEM_ID = :2 AND A.ITM_ID_VNDR = :3 AND A.ITM_VNDR_PRIORITY = 1 AND B.UNIT_OF_MEASURE = :4 AND B.CONVERSION_RATE = :5", &VendorId, &InvItemId, &ItmIdVndr, &UOM, &ConvRate, &VendorId_check);
If None(&VendorId_check) Then;
&Error = "Y";
MessageBox(0, "", 0, 0, &VendorId | " " | &InvItemId | " " | &ItmIdVndr | " " | &UOM | " " | &ConvRate | " " | &PriceVndr | " " | &Effdt | " " | &ItmIdVndrNew);
Else;
&CurrentDateTime = %Datetime;
&Oprid = %OperatorId;
&RECITEM = CreateRecord(Record.ITM_VNDR_UOM_PR);
/*8/8/2012 - CHC_PO_96588 - Begin */
/*SQLExec("SELECT TO_CHAR(C.EFFDT,'DD-MON-YYYY') FROM PS_ITM_VNDR_UOM_PR C WHERE C.INV_ITEM_ID = :1 AND C.VENDOR_ID = :2 AND C.UNIT_OF_MEASURE = :3 AND C.EFFDT = (SELECT MAX(C1.EFFDT) FROM PS_ITM_VNDR_UOM_PR C1 WHERE C.SETID = C1.SETID AND C.INV_ITEM_ID = C1.INV_ITEM_ID AND C.VENDOR_SETID = C1.VENDOR_SETID AND C.VENDOR_ID = C1.VENDOR_ID AND C.VNDR_LOC = C1.VNDR_LOC AND C.UNIT_OF_MEASURE = C1.UNIT_OF_MEASURE AND C.CURRENCY_CD = C1.CURRENCY_CD AND C.QTY_MIN = C1.QTY_MIN) ", &InvItemId, &VendorId, &UOM, &MaxEffdt);*/
SQLExec("SELECT C.EFFDT FROM PS_ITM_VNDR_UOM_PR C WHERE C.INV_ITEM_ID = :1 AND C.VENDOR_ID = :2 AND C.UNIT_OF_MEASURE = :3 AND C.EFFDT = (SELECT MAX(C1.EFFDT) FROM PS_ITM_VNDR_UOM_PR C1 WHERE C.SETID = C1.SETID AND C.INV_ITEM_ID = C1.INV_ITEM_ID AND C.VENDOR_SETID = C1.VENDOR_SETID AND C.VENDOR_ID = C1.VENDOR_ID AND C.VNDR_LOC = C1.VNDR_LOC AND C.UNIT_OF_MEASURE = C1.UNIT_OF_MEASURE AND C.CURRENCY_CD = C1.CURRENCY_CD AND C.QTY_MIN = C1.QTY_MIN) ", &InvItemId, &VendorId, &UOM, &MaxEffdt);
/*CHC_PO_96588 - End */
SQLExec("%SelectAll(:1) WHERE INV_ITEM_ID = :2 AND VENDOR_ID = :3 AND UNIT_OF_MEASURE = :4 AND (CONVERT(CHAR(10),EFFDT,121)) = :5", &RECITEM, &InvItemId, &VendorId, &UOM, &MaxEffdt, &RECITEM);
/*SQLExec("%SelectAll(:1) WHERE INV_ITEM_ID = :2 AND VENDOR_ID = :3 AND UNIT_OF_MEASURE = :4 AND EFFDT = :5", &RECITEM, &InvItemId, &VendorId, &UOM, &MaxEffdt, &RECITEM); */
&new_UNIT_OF_MEASURE = &RECITEM.UNIT_OF_MEASURE.Value;
&REC = CreateRecord(Record.ITM_VNDR_UOM_PR);
&REC.SETID.Value = &RECITEM.SETID.Value;
&REC.INV_ITEM_ID.Value = &RECITEM.INV_ITEM_ID.Value;
&REC.VENDOR_SETID.Value = &RECITEM.VENDOR_SETID.Value;
&REC.VENDOR_ID.Value = &RECITEM.VENDOR_ID.Value;
&REC.VNDR_LOC.Value = &RECITEM.VNDR_LOC.Value;
&REC.UNIT_OF_MEASURE.Value = &RECITEM.UNIT_OF_MEASURE.Value;
&REC.CURRENCY_CD.Value = &RECITEM.CURRENCY_CD.Value;
&REC.QTY_MIN.Value = &RECITEM.QTY_MIN.Value;
&REC.EFFDT.Value = &Effdt;
&REC.EFF_STATUS.Value = &RECITEM.EFF_STATUS.Value;
&REC.PRICE_VNDR.Value = &PriceVndr;
&REC.PCT_UNIT_PRC_TOL.Value = &RECITEM.PCT_UNIT_PRC_TOL.Value;
&REC.PCT_EXT_PRC_TOL.Value = &RECITEM.PCT_EXT_PRC_TOL.Value;
&REC.USE_STD_TOLERANCES.Value = &RECITEM.USE_STD_TOLERANCES.Value;
&REC.QTY_RECV_TOL_PCT.Value = &RECITEM.QTY_RECV_TOL_PCT.Value;
&REC.UNIT_PRC_TOL_L.Value = &RECITEM.UNIT_PRC_TOL_L.Value;
&REC.PCT_UNIT_PRC_TOL_L.Value = &RECITEM.PCT_UNIT_PRC_TOL_L.Value;
&REC.EXT_PRC_TOL_L.Value = &RECITEM.EXT_PRC_TOL_L.Value;
&REC.PCT_EXT_PRC_TOL_L.Value = &RECITEM.PCT_EXT_PRC_TOL_L.Value;
&REC.BU_PRICE_STATUS.Value = "2";
&REC.STD_PRICE_STATUS.Value = "2";
&REC.LEAD_TIME.Value = &RECITEM.LEAD_TIME.Value;
&REC.OPRID_MODIFIED_BY.Value = &Oprid;
&REC.LAST_DTTM_UPDATE.Value = &CurrentDateTime;
&REC.PRICE_CHANGE.Value = &RECITEM.PRICE_CHANGE.Value;
&REC.Insert();
/* 10/30/2014 - Writes line if good */
/*MessageBox(0, "", 0, 0, &VendorId | " " | &InvItemId | " " | &ItmIdVndr | " " | &UOM | " " | &ConvRate | " " | &PriceVndr | " " | &Effdt);*/
End-If;
End-While;
/* 1/7/2020 BEGIN Changes for ITEM_ID_VNDR */
&SQL2 = CreateSQL("SELECT VENDOR_ID, INV_ITEM_ID, ITM_ID_VNDR, UNIT_OF_MEASURE, CONVERSION_RATE, PRICE_VNDR, %DateOut(EFFDT), ITM_ID_VNDR_NEW FROM PS_GH_ITM_PR_UPDT ORDER BY VENDOR_ID, INV_ITEM_ID, ITM_ID_VNDR", &VendorId, &InvItemId, &ItmIdVndr, &UOM, &ConvRate, &PriceVndr, &Effdt, &ItmIdVndrNew);
While &SQL2.Fetch(&VendorId, &InvItemId, &ItmIdVndr, &UOM, &ConvRate, &PriceVndr, &Effdt, &ItmIdVndrNew)
If None(&ItmIdVndrNew) Then;
&Error = "Y";
MessageBox(0, "", 0, 0, &VendorId | " " | &InvItemId | " " | &ItmIdVndr | " " | &UOM | " " | &ConvRate | " " | &PriceVndr | " " | &Effdt | " " | &ItmField | " " | &ItmIdVndrNew);
MessageBox(0, "", 0, 0, "**** INSIDE MAIN IF CONDITION ****");
Else;
MessageBox(0, "", 0, 0, "**** INSIDE ELSE CONDITION ****");
&REC1 = CreateRecord(Record.ITM_VENDOR);
&REC1.ITM_ID_VNDR.Value = &ItmIdVndrNew;
&REC1.Update();
End-If;
End-While;
/* 1/7/2020 END Changes for ITEM_ID_VNDR */
MessageBox(0, "", 0, 0, "**** END OF VALIDATION ERRORS ****");
MessageBox(0, "", 0, 0, " ");
UPDATE: I can see in the Trace file that I am not picking up the table's key fields while trying to update. I am thinking this is part of the problem...
8830 10:51:28.860 0.000000 Cur#1.23796.FSDEV92C RC=0 Dur=0.000000 COM Stmt=UPDATE PS_ITM_VENDOR SET ITM_ID_VNDR=:1 WHERE SETID=:2 AND INV_ITEM_ID=:3 AND VENDOR_SETID=:4 AND VENDOR_ID=:5
8831 10:51:28.861 0.000000 Cur#1.23796.FSDEV92C RC=0 Dur=0.000000 Bind-1 type=2 length=7 value=1234567
8832 10:51:28.861 0.001000 Cur#1.23796.FSDEV92C RC=0 Dur=0.000000 Bind-2 type=2 length=1 value=
8833 10:51:28.862 0.000000 Cur#1.23796.FSDEV92C RC=0 Dur=0.000000 Bind-3 type=2 length=1 value=
8834 10:51:28.862 0.001000 Cur#1.23796.FSDEV92C RC=0 Dur=0.000000 Bind-4 type=2 length=1 value=
8835 10:51:28.863 0.000000 Cur#1.23796.FSDEV92C RC=0 Dur=0.000000 Bind-5 type=2 length=1 value=
8836 10:51:28.864 0.001000 Cur#1.23796.FSDEV92C RC=0 Dur=0.001000 EXE
8837 10:51:28.865 0.000000 Cur#1.23796.FSDEV92C RC=0 Dur=0.000000 ROW #rows=0
8838 10:51:28.865 0.001000 Cur#5.23796.FSDEV92C RC=0 Dur=0.000000 Fetch
You are only setting &REC1.ITM_ID_VNDR.Value.
You need to set all the keys in &REC1 before calling the Update() method.
Think I have discovered the issue, I needed to bind &REC1 to &REC2 as follows:
&REC1 = CreateRecord(Record.ITM_VENDOR);
&REC2 = CreateRecord(Record.ITM_VENDOR);
.....
&REC2.Update(&REC1);

PeopleSoft Subquery not picking up correct leave plans

I'm attempting to build a report in PeopleSoft's Query Manager that has future and current employees on it. I want to be able to find the employees who do not have leave plans, specifically 50 and 52. I thought I was on the right track with the following BUT after auditing my report it is bringing in people who HAVE 50 and 52. I think it has to do with the subquery (SQL below).
Here are some pictures of query manager:
SELECT DISTINCT B.COMPANY, A.EMPLID, A.NAME, B.FULL_PART_TIME, B.REG_TEMP, C.DESCR, D.PLAN_TYPE, (CASE WHEN B.REG_TEMP = 'T' THEN '' WHEN C.DESCR = 'Intern' THEN '' WHEN C.DESCR = 'PenFed Intern' THEN '' ELSE 'Check records/give Leave' END), CONVERT(CHAR(10),SUBSTRING(CONVERT(CHAR,GETDATE(),121), 1, 10),121)), (CONVERT(CHAR(10),SUBSTRING(CONVERT(CHAR,GETDATE(),121), 1, 10),121)), (CONVERT(CHAR(10),SUBSTRING(CONVERT(CHAR,GETDATE(),121), 1, 10),121))
FROM (PS_PERSONAL_DATA A LEFT OUTER JOIN (PS_LEAVE_PLAN D INNER JOIN PS_EMPLMT_SRCH_QRY D1 ON (D.EMPLID = D1.EMPLID AND D.EMPL_RCD = D1.EMPL_RCD AND D1.OPRID = 'XXXXXXXX' )) ON A.EMPLID = D.EMPLID ), PS_PFC_JOB_VW B, PS_JOBCODE_TBL C, PS_SET_CNTRL_REC C2
WHERE ( C.JOBCODE = B.JOBCODE
AND C2.SETCNTRLVALUE = B.BUSINESS_UNIT
AND C2.RECNAME = 'JOBCODE_TBL'
AND C2.SETID = C.SETID
AND ( A.EMPLID = B.EMPLID
AND ( B.EFFDT =
(SELECT MAX(B_ED.EFFDT) FROM PS_PFC_JOB_VW B_ED
WHERE B.EMPLID = B_ED.EMPLID
AND B.EMPL_RCD = B_ED.EMPL_RCD
AND B_ED.EFFDT <= SUBSTRING(CONVERT(CHAR,GETDATE(),121), 1, 10))
AND B.EFFSEQ =
(SELECT MAX(B_ES.EFFSEQ) FROM PS_PFC_JOB_VW B_ES
WHERE B.EMPLID = B_ES.EMPLID
AND B.EMPL_RCD = B_ES.EMPL_RCD
AND B.EFFDT = B_ES.EFFDT)
OR ( B.EFFDT =
(SELECT MIN(B_ED.EFFDT) FROM PS_PFC_JOB_VW B_ED
WHERE B.EMPLID = B_ED.EMPLID
AND B.EMPL_RCD = B_ED.EMPL_RCD
AND B_ED.EFFDT >= SUBSTRING(CONVERT(CHAR,GETDATE(),121), 1, 10))
AND B.EFFSEQ =
(SELECT MAX(B_ES.EFFSEQ) FROM PS_PFC_JOB_VW B_ES
WHERE B.EMPLID = B_ES.EMPLID
AND B.EMPL_RCD = B_ES.EMPL_RCD
AND B.EFFDT = B_ES.EFFDT)
AND B.ACTION IN ('HIR','REH','REI')))
AND B.EMPL_STATUS IN ('A','L','P')
AND B.PER_ORG = 'EMP'
AND C.EFFDT =
(SELECT MAX(C_ED.EFFDT) FROM PS_JOBCODE_TBL C_ED
WHERE C.SETID = C_ED.SETID
AND C.JOBCODE = C_ED.JOBCODE
AND C_ED.EFFDT <= B.EFFDT)
AND A.EMPLID NOT IN (SELECT E.EMPLID
FROM PS_LEAVE_PLAN E, PS_EMPLMT_SRCH_QRY E1
WHERE E.EMPLID = E1.EMPLID
AND E.EMPL_RCD = E1.EMPL_RCD
AND E1.OPRID = 'XXXXXXXX'
AND ( E.EFFDT =
(SELECT MAX(E_ED.EFFDT) FROM PS_LEAVE_PLAN E_ED
WHERE E.EMPLID = E_ED.EMPLID
AND E.EMPL_RCD = E_ED.EMPL_RCD
AND E.PLAN_TYPE = E_ED.PLAN_TYPE
AND E.BENEFIT_NBR = E_ED.BENEFIT_NBR
AND E_ED.EFFDT <= SUBSTRING(CONVERT(CHAR,GETDATE(),121), 1, 10))
AND ( E.PLAN_TYPE = '50'
OR E.PLAN_TYPE = '52') )) ))
Where am I going wrong here?

Color cells depending of their value for each row of a data frame

I have a data frame which looks like this:
header1 header2 header3 header4 ...
rowname1 1 2 3 4
rowname2 4 3 2 1
rowname3 2 4 1 3
rowname4 1 4 3 2
...
I would like to make a color gradient depending of the values for each row. Typically I would like the maximum value of each row to be colored green, the minimum value of each row colored red, and the other cells to be colored gradually depending of their value (second worst would be orange, second best would be yellow, etc ...).
An example of what I would like to obtain:
Could you please help me in solving this matter ?
Here is a possibility with DT.
dat <- data.frame(
V1 = rpois(6,5),
V2 = rpois(6,5),
V3 = rpois(6,5),
V4 = rpois(6,5),
V5 = rpois(6,5),
V6 = rpois(6,5)
)
library(DT)
js <- c(
"function(row, data, num, index){",
" data.shift();", # remove row name
" var min = Math.min.apply(null, data);",
" var max = Math.max.apply(null, data);",
" for(var i=0; i<data.length; i++){",
" var f = (data[i] - min)/(max-min);",
" var h = 120*f;",
" var color = 'hsl(' + h + ', 100%, 50%)';",
" $('td:eq('+(i+1)+')', row).css('background-color', color);",
" }",
"}"
)
datatable(dat, options = list(rowCallback = JS(js)))
To add black borders, do
datatable(dat, options = list(rowCallback = JS(js))) %>%
formatStyle(1:(ncol(dat)-1), `border-right` = "solid 1px")
The above solution assumes that you display the row names in the table. If you don't want to display the row names, do:
js <- c(
"function(row, data, num, index){",
" var min = Math.min.apply(null, data);",
" var max = Math.max.apply(null, data);",
" for(var i=0; i<data.length; i++){",
" var f = (data[i] - min)/(max-min);",
" var h = 120*f;",
" var color = 'hsl(' + h + ', 100%, 50%)';",
" $('td:eq('+i+')', row).css('background-color', color);",
" }",
"}"
)
datatable(dat, rownames = FALSE, options = list(rowCallback = JS(js)))
Edit
As requested by the OP in the chat, here is a variant. Instead of generating a color proportional to the cell value, it generates a color proportional to the rank of the cell value.
js <- c(
"function(row, data, num, index){",
" data.shift();", # remove row name
" var data_uniq = data.filter(function(item, index) {",
" if(data.indexOf(item) == index){",
" return item;",
" }}).sort(function(a,b){return a-b});",
" var n = data_uniq.length;",
" var ranks = data.slice().map(function(v){ return data_uniq.indexOf(v) });",
" for(var i=0; i<data.length; i++){",
" var f = ranks[i]/(n-1);",
" var h = 120*f;",
" var color = 'hsl(' + h + ', 100%, 50%)';",
" $('td:eq('+(i+1)+')', row).css('background-color', color);",
" }",
"}"
)
dat <- as.data.frame(matrix(round(rnorm(24),2), ncol=8))
datatable(dat, options = list(rowCallback = JS(js)))
I've found that the colors are more distinct by replacing var h = 120*f; with
var h = 60*(1 + Math.tan(2*f-1)/Math.tan(1));

Export data from database

I have few tables in database that are having huge amount of data. My need is
1 : To query data exist for more than one year.
2 : Export and archive them to some file.
3 : At any point of time I can insert those data back to database.
The data may or may not contain COMMA, so not sure if I should export them to csv format.
Which is the best file format I should go for ??
What should be the file size limitation here ??
This script exports rows from specified tables to INSERT statement for any tables structure. So, you'll just need to copy the result and run it in sql document of SSMS -
DECLARE
#TableName SYSNAME
, #ObjectID INT
, #IsImportIdentity BIT = 1
DECLARE [tables] CURSOR READ_ONLY FAST_FORWARD LOCAL FOR
SELECT
'[' + s.name + '].[' + t.name + ']'
, t.[object_id]
FROM (
SELECT DISTINCT
t.[schema_id]
, t.[object_id]
, t.name
FROM sys.objects t WITH (NOWAIT)
JOIN sys.partitions p WITH (NOWAIT) ON p.[object_id] = t.[object_id]
WHERE p.[rows] > 0
AND t.[type] = 'U'
) t
JOIN sys.schemas s WITH (NOWAIT) ON t.[schema_id] = s.[schema_id]
WHERE t.name IN ('<your table name>')
OPEN [tables]
FETCH NEXT FROM [tables] INTO
#TableName
, #ObjectID
DECLARE
#SQLInsert NVARCHAR(MAX)
, #SQLColumns NVARCHAR(MAX)
, #SQLTinyColumns NVARCHAR(MAX)
WHILE ##FETCH_STATUS = 0 BEGIN
SELECT
#SQLInsert = ''
, #SQLColumns = ''
, #SQLTinyColumns = ''
;WITH cols AS
(
SELECT
c.name
, datetype = t.name
, c.column_id
FROM sys.columns c WITH (NOWAIT)
JOIN sys.types t WITH (NOWAIT) ON c.system_type_id = t.system_type_id AND c.user_type_id = t.user_type_id
WHERE c.[object_id] = #ObjectID
AND (c.is_identity = 0 OR #IsImportIdentity = 1)
AND c.is_computed = 0
AND t.name NOT IN ('xml', 'geography', 'geometry', 'hierarchyid')
)
SELECT
#SQLInsert = 'INSERT INTO ' + #TableName + ' (' + STUFF((
SELECT ', [' + c.name + ']'
FROM cols c
ORDER BY c.column_id
FOR XML PATH, TYPE, ROOT).value('.', 'NVARCHAR(MAX)'), 1, 2, '') + ')'
, #SQLTinyColumns = STUFF((
SELECT ', ' + c.name
FROM cols c
ORDER BY c.column_id
FOR XML PATH, TYPE, ROOT).value('.', 'NVARCHAR(MAX)'), 1, 2, '')
, #SQLColumns = STUFF((SELECT CHAR(13) +
CASE
WHEN c.datetype = 'uniqueidentifier'
THEN ' + '', '' + ISNULL('''''''' + CAST([' + c.name + '] AS VARCHAR(MAX)) + '''''''', ''NULL'')'
WHEN c.datetype IN ('nvarchar', 'varchar', 'nchar', 'char', 'varbinary', 'binary')
THEN ' + '', '' + ISNULL('''''''' + CAST(REPLACE([' + c.name + '], '''''''', '''''''''''' ) AS NVARCHAR(MAX)) + '''''''', ''NULL'')'
WHEN c.datetype = 'datetime'
THEN ' + '', '' + ISNULL('''''''' + CONVERT(VARCHAR, [' + c.name + '], 120) + '''''''', ''NULL'')'
ELSE
' + '', '' + ISNULL(CAST([' + c.name + '] AS NVARCHAR(MAX)), ''NULL'')'
END
FROM cols c
ORDER BY c.column_id
FOR XML PATH, TYPE, ROOT).value('.', 'NVARCHAR(MAX)'), 1, 10, 'CHAR(13) + '', ('' +')
DECLARE #SQL NVARCHAR(MAX) = '
SET NOCOUNT ON;
DECLARE
#SQL NVARCHAR(MAX) = ''''
, #x INT = 1
, #count INT = (SELECT COUNT(1) FROM ' + #TableName + ')
IF EXISTS(
SELECT 1
FROM tempdb.dbo.sysobjects
WHERE ID = OBJECT_ID(''tempdb..#import'')
)
DROP TABLE #import;
SELECT ' + #SQLTinyColumns + ', ''RowNumber'' = ROW_NUMBER() OVER (ORDER BY ' + #SQLTinyColumns + ')
INTO #import
FROM ' + #TableName + '
WHILE #x < #count BEGIN
SELECT #SQL = ''VALUES '' + STUFF((
SELECT ' + #SQLColumns + ' + '')''' + '
FROM #import
WHERE RowNumber BETWEEN #x AND #x + 9
FOR XML PATH, TYPE, ROOT).value(''.'', ''NVARCHAR(MAX)''), 1, 2, CHAR(13) + '' '') + '';''
PRINT(''' + #SQLInsert + ''')
PRINT(#SQL)
SELECT #x = #x + 10
END'
EXEC sys.sp_executesql #SQL
FETCH NEXT FROM [tables] INTO
#TableName
, #ObjectID
END
CLOSE [tables]
DEALLOCATE [tables]
In output you get something like this (AdventureWorks.Person.Address):
INSERT INTO [Person].[Address] ([AddressID], [AddressLine1], [AddressLine2], [City], [StateProvinceID], [PostalCode], [rowguid], [ModifiedDate])
VALUES
(1, '1970 Napa Ct.', NULL, 'Bothell', 79, '98011', '9AADCB0D-36CF-483F-84D8-585C2D4EC6E9', '2002-01-04 00:00:00')
, (2, '9833 Mt. Dias Blv.', NULL, 'Bothell', 79, '98011', '32A54B9E-E034-4BFB-B573-A71CDE60D8C0', '2003-01-01 00:00:00')
, (3, '7484 Roundtree Drive', NULL, 'Bothell', 79, '98011', '4C506923-6D1B-452C-A07C-BAA6F5B142A4', '2007-04-08 00:00:00')
, (4, '9539 Glenside Dr', NULL, 'Bothell', 79, '98011', 'E5946C78-4BCC-477F-9FA1-CC09DE16A880', '2003-03-07 00:00:00')
, (5, '1226 Shoe St.', NULL, 'Bothell', 79, '98011', 'FBAFF937-4A97-4AF0-81FD-B849900E9BB0', '2003-01-20 00:00:00')
, (6, '1399 Firestone Drive', NULL, 'Bothell', 79, '98011', 'FEBF8191-9804-44C8-877A-33FDE94F0075', '2003-03-17 00:00:00')
, (7, '5672 Hale Dr.', NULL, 'Bothell', 79, '98011', '0175A174-6C34-4D41-B3C1-4419CD6A0446', '2004-01-12 00:00:00')
, (8, '6387 Scenic Avenue', NULL, 'Bothell', 79, '98011', '3715E813-4DCA-49E0-8F1C-31857D21F269', '2003-01-18 00:00:00')
, (9, '8713 Yosemite Ct.', NULL, 'Bothell', 79, '98011', '268AF621-76D7-4C78-9441-144FD139821A', '2006-07-01 00:00:00')
, (10, '250 Race Court', NULL, 'Bothell', 79, '98011', '0B6B739D-8EB6-4378-8D55-FE196AF34C04', '2003-01-03 00:00:00');
UPDATE:
And this script exports rows from specified tables to CSV format in output window for any tables structure.
DECLARE
#TableName SYSNAME
, #ObjectID INT
DECLARE [tables] CURSOR READ_ONLY FAST_FORWARD LOCAL FOR
SELECT
'[' + s.name + '].[' + t.name + ']'
, t.[object_id]
FROM (
SELECT DISTINCT
t.[schema_id]
, t.[object_id]
, t.name
FROM sys.objects t WITH (NOWAIT)
JOIN sys.partitions p WITH (NOWAIT) ON p.[object_id] = t.[object_id]
WHERE p.[rows] > 0
AND t.[type] = 'U'
) t
JOIN sys.schemas s WITH (NOWAIT) ON t.[schema_id] = s.[schema_id]
WHERE t.name IN ('<your table name>')
OPEN [tables]
FETCH NEXT FROM [tables] INTO
#TableName
, #ObjectID
DECLARE
#SQLInsert NVARCHAR(MAX)
, #SQLColumns NVARCHAR(MAX)
, #SQLTinyColumns NVARCHAR(MAX)
WHILE ##FETCH_STATUS = 0 BEGIN
SELECT
#SQLInsert = ''
, #SQLColumns = ''
, #SQLTinyColumns = ''
;WITH cols AS
(
SELECT
c.name
, datetype = t.name
, c.column_id
FROM sys.columns c WITH (NOWAIT)
JOIN sys.types t WITH (NOWAIT) ON c.system_type_id = t.system_type_id AND c.user_type_id = t.user_type_id
WHERE c.[object_id] = #ObjectID
AND c.is_computed = 0
AND t.name NOT IN ('xml', 'geography', 'geometry', 'hierarchyid')
)
SELECT
#SQLTinyColumns = STUFF((
SELECT ', [' + c.name + ']'
FROM cols c
ORDER BY c.column_id
FOR XML PATH, TYPE, ROOT).value('.', 'NVARCHAR(MAX)'), 1, 2, '')
, #SQLColumns = STUFF((SELECT CHAR(13) +
CASE
WHEN c.datetype = 'uniqueidentifier'
THEN ' + '';'' + ISNULL('''' + CAST([' + c.name + '] AS VARCHAR(MAX)) + '''', ''NULL'')'
WHEN c.datetype IN ('nvarchar', 'varchar', 'nchar', 'char', 'varbinary', 'binary')
THEN ' + '';'' + ISNULL('''' + CAST(REPLACE([' + c.name + '], '''', '''''''') AS NVARCHAR(MAX)) + '''', ''NULL'')'
WHEN c.datetype = 'datetime'
THEN ' + '';'' + ISNULL('''' + CONVERT(VARCHAR, [' + c.name + '], 120) + '''', ''NULL'')'
ELSE
' + '';'' + ISNULL(CAST([' + c.name + '] AS NVARCHAR(MAX)), ''NULL'')'
END
FROM cols c
ORDER BY c.column_id
FOR XML PATH, TYPE, ROOT).value('.', 'NVARCHAR(MAX)'), 1, 10, 'CHAR(13) + '''' +')
DECLARE #SQL NVARCHAR(MAX) = '
SET NOCOUNT ON;
DECLARE
#SQL NVARCHAR(MAX) = ''''
, #x INT = 1
, #count INT = (SELECT COUNT(1) FROM ' + #TableName + ')
IF EXISTS(
SELECT 1
FROM tempdb.dbo.sysobjects
WHERE ID = OBJECT_ID(''tempdb..#import'')
)
DROP TABLE #import;
SELECT ' + #SQLTinyColumns + ', ''RowNumber'' = ROW_NUMBER() OVER (ORDER BY ' + #SQLTinyColumns + ')
INTO #import
FROM ' + #TableName + '
WHILE #x < #count BEGIN
SELECT #SQL = STUFF((
SELECT ' + #SQLColumns + ' + ''''' + '
FROM #import
WHERE RowNumber BETWEEN #x AND #x + 9
FOR XML PATH, TYPE, ROOT).value(''.'', ''NVARCHAR(MAX)''), 1, 1, '''')
PRINT(#SQL)
SELECT #x = #x + 10
END'
EXEC sys.sp_executesql #SQL
FETCH NEXT FROM [tables] INTO
#TableName
, #ObjectID
END
CLOSE [tables]
DEALLOCATE [tables]
In output you get something like this (AdventureWorks.Person.Person):
1;EM;0;NULL;Ken;J;Sánchez;NULL;0;92C4279F-1207-48A3-8448-4636514EB7E2;2003-02-08 00:00:00
2;EM;0;NULL;Terri;Lee;Duffy;NULL;1;D8763459-8AA8-47CC-AFF7-C9079AF79033;2002-02-24 00:00:00
3;EM;0;NULL;Roberto;NULL;Tamburello;NULL;0;E1A2555E-0828-434B-A33B-6F38136A37DE;2001-12-05 00:00:00
4;EM;0;NULL;Rob;NULL;Walters;NULL;0;F2D7CE06-38B3-4357-805B-F4B6B71C01FF;2001-12-29 00:00:00
5;EM;0;Ms.;Gail;A;Erickson;NULL;0;F3A3F6B4-AE3B-430C-A754-9F2231BA6FEF;2002-01-30 00:00:00
6;EM;0;Mr.;Jossef;H;Goldberg;NULL;0;0DEA28FD-EFFE-482A-AFD3-B7E8F199D56F;2002-02-17 00:00:00
Try using the bcp command line utility, which is very efficient at handling import/export for large data sets:
bcp "select * from [YourTable]" queryout data.dat -n -S YourServer -d "YourDatabase" -T
-T means Trusted Authentication. -n means native format, so you don't need to worry about data types, commas, etc. However, this does mean you can't view the data in an editor; it's only available for loading back into SQL Server. You can use -c instead if you want CSV format.
To import back in:
bcp "[YourTable]" in data.dat -n -S YourServer -d "YourDatabase" -T

Resources