Query object not working as expected? - axapta

This code should be able to run on any AX system (change item & warehouse). The issue is that CustInvoiceJour is not being returned sometimes. What is odd, is if I just do a "select custInvoiceJour" with the same relations, it DOES find it? How is this possible?
static void Job59(Args _args)
{
CustInvoiceTrans custInvoiceTrans;
CustInvoiceJour custInvoiceJour;
InventTable inventTable;
QueryBuildRange rangeItem;
Query query;
QueryBuildDataSource qbds1;
QueryBuildDataSource qbds2;
QueryBuildDataSource qbds3;
QueryRun qr;
;
query = new Query();
qbds1 = query.addDataSource(tablenum(CustInvoiceTrans));
qbds2 = qbds1.addDataSource(tablenum(CustInvoiceJour));
qbds2.relations(true);
qbds2.addRange(fieldnum(CustInvoiceJour, SalesType)).value('!' + enum2str(SalesType::ReturnItem));
rangeItem = qbds1.addRange(fieldnum(CustInvoiceTrans, ItemId));
qbds1.addRange(fieldnum(CustInvoiceTrans, InvoiceDate)).value(queryRange(#'8/1/2011', #'8/31/2011'));
qbds2.orderMode(OrderMode::OrderBy);
qbds2.addOrderByField(fieldnum(CustInvoiceJour, DlvCountryRegionId));
qbds2.addOrderByField(fieldnum(CustInvoiceJour, DlvState));
qbds3 = qbds1.addDataSource(tablenum(InventDim));
qbds3.relations(true);
qbds3.joinMode(JoinMode::ExistsJoin);
qbds3.addRange(fieldnum(InventDim, InventLocationId)).value(SysQuery::value('FG'));
select firstonly inventTable
where inventTable.ItemId == '44831';
info (strfmt("%1", inventTable.ItemId));
rangeItem.value(inventTable.ItemId);
qr = new QueryRun(query);
while (qr.next())
{
custInvoiceTrans = qr.get(tablenum(CustInvoiceTrans));
custInvoiceJour = qr.get(tablenum(CustInvoiceJour));
if (!custInvoiceJour)
{
info ("Not found");
select firstonly custInvoiceJour
where custInvoiceJour.SalesId == custInvoiceTrans.SalesId &&
custInvoiceJour.InvoiceId == custInvoiceTrans.InvoiceId &&
custInvoiceJour.InvoiceDate == custInvoiceTrans.InvoiceDate &&
custInvoiceJour.numberSequenceGroup == custInvoiceTrans.numberSequenceGroup;
if (custInvoiceJour)
info("Found it");
}
}
}
The debugger shows these as the queries:
NAME:
qbds1
VALUE:
SELECT * FROM CustInvoiceTrans ORDER BY CustInvoiceJour.DlvCountryRegionId ASC, CustInvoiceJour.DlvState ASC WHERE ((ItemId = N'44831')) AND ((InvoiceDate>={ts '2011-08-01 00:00:00.000'} AND InvoiceDate<={ts '2011-08-31 00:00:00.000'})) EXISTS JOIN * FROM InventDim WHERE CustInvoiceTrans.InventDimId = InventDim.inventDimId AND ((InventLocationId = N'FG'))
NAME:
qbds2
VALUE:
SELECT * FROM CustInvoiceJour WHERE CustInvoiceTrans.SalesId = CustInvoiceJour.SalesId AND CustInvoiceTrans.InvoiceId = CustInvoiceJour.InvoiceId AND CustInvoiceTrans.InvoiceDate = CustInvoiceJour.InvoiceDate AND CustInvoiceTrans.numberSequenceGroup = CustInvoiceJour.numberSequenceGroup AND ((NOT (SalesType = 4)))
NAME:
qbds3
VALUE:
SELECT * FROM InventDim WHERE CustInvoiceTrans.InventDimId = InventDim.inventDimId AND ((InventLocationId = N'FG'))

Your qbds1 value doesn't show JOIN * FROM CustInvoiceJour WHERE ... (joined qbds2).
Add qbds2.fetchMode(QueryFetchMode::One2One); to your code and everything should be alright.
P.S. I would suggest to do it the other way round: CustInvoiceJour in qbds1, and CustInvoiceTrans in qbds2 (with default fetchMode), then you wouldn't have this problem at all.

Related

Chain of command doesn't work on Data Provider

I am trying to extend FreeTextInvoiceDP to add new fields to the report, I have created a chain of command, but when I run it the process does not go through the extension. I have debug it and effectively the extension doesn't work, is there anything that I have forgotten?
my extension:
[ExtensionOf(classStr(FreeTextInvoiceDP))]
final class FreeTextInvoiceDP_Cls_ARQ_CONCCo_Extension
{
protected void populateFreeTextInvoiceHeaderFooterTmp(CustInvoiceJour _custInvoiceJour,
CompanyInfo _companyInfo)
{
CustInvoiceTable custInvoiceTable;
CustInvoiceTrans custInvoiceTrans;
CustTable custTable;
TaxTrans taxTrans;
next populateFreeTextInvoiceHeaderFooterTmp(_custInvoiceJour, _companyInfo);
custInvoiceTable = _custInvoiceJour.custInvoiceTable();
custTable = CustTable::find(_custInvoiceJour.OrderAccount);
freeTextInvoiceHeaderFooterTmp.ARQ_CONCCo_InvoiceId = custInvoiceTable.InvoiceId;
freeTextInvoiceHeaderFooterTmp.ARQ_CONCCo_InvoiceDate = custInvoiceTable.InvoiceDate;
freeTextInvoiceHeaderFooterTmp.ARQ_CONCCo_DueDate = custInvoiceTable.DueDate;
freeTextInvoiceHeaderFooterTmp.ARQ_CONCCo_Currency = custInvoiceTable.CurrencyCode;
freeTextInvoiceHeaderFooterTmp.ARQ_CONCCo_Address = DirParty::primaryPostalAddress(custTable.party).address;
freeTextInvoiceHeaderFooterTmp.ARQ_CONCCo_VatNum = custInvoiceTable.VatNum;
freeTextInvoiceHeaderFooterTmp.ARQ_CONCCo_CustName = custInvoiceTable.Name;
freeTextInvoiceHeaderFooterTmp.ARQ_CONCCo_CompanyLogo = CompanyImage::FindByRecord(CompanyInfo::find()).Image;
}
protected void populateFreeTextInvoiceTmp(CustInvoiceJour _custInvoiceJour, CustInvoiceTrans _custInvoiceTrans, TaxSpec _taxSpec, CustPaymSchedLine _custPaymSchedLine, CustTrans _prepaymentCustTrans, TaxTrans _prepaymentTaxTrans)
{
TaxTrans taxTrans;
next populateFreeTextInvoiceTmp(_custInvoiceJour, _custInvoiceTrans, _taxSpec, _custPaymSchedLine, _prepaymentCustTrans, _prepaymentTaxTrans);
select firstonly taxTrans
where taxTrans.SourceRecId == _custInvoiceTrans.RecId
&& taxTrans.SourceTableId == _custInvoiceTrans.TableId;
freeTextInvoiceTmp.ARQ_CONCCo_TaxCode = taxTrans.TaxCode;
}
protected void insertIntoFreeTextInvoiceHeaderFooterTmp(CustInvoiceJour _custInvoiceJour, CompanyInfo _companyInfo)
{
TaxTrans taxTrans;
CustInvoiceTrans custInvoiceTrans;
next insertIntoFreeTextInvoiceHeaderFooterTmp(_custInvoiceJour, _companyInfo);
while select custInvoiceTrans
where custInvoiceTrans.InvoiceId == _custInvoiceJour.InvoiceId
join sum(TaxBaseAmount), sum(TaxAmount), taxcode, taxvalue from taxTrans
group by taxTrans.TaxCode, taxtrans.taxvalue
where taxTrans.SourceRecId == custinvoicetrans.recid
&& taxtrans.sourcetableid == custinvoicetrans.tableid
{
FreeTextInvoiceLocalizationTmp.caption = taxtrans.taxcode;
FreeTextInvoiceLocalizationTmp.cashdisc = taxtrans.taxvalue;
FreeTextInvoiceLocalizationTmp.cashdiscamount = taxtrans.taxbaseamount * -1;
FreeTextInvoiceLocalizationTmp.discamount = taxtrans.taxamount * -1;
freeTextInvoiceLocalizationTmp.insert();
freeTextInvoiceLocalizationTmp.clear();
}
}
}

How to build or condition on datasorce in the code?

I have two tables. Lets call them Table1 and Table2. I need to create in the code query like.
Select * from Table1
exists join Table2 where
Table1.Key == Table2.Key &&
(Table1.A == '1' || Table2.C == '2')
So to transfer to code I tried:
Query q;
QueryBuildDataSource qbd;
QueryBuildDataSource ofQbds;
QueryBuildRange qbr;
str range;
Table1 test;
QueryRun qr;
q = new Query();
qbd = q.addDataSource(tableNum(Table1));
qbd .name('Table1');
ofQbds = qbd.addDataSource(tableNum(Table2));
ofQbds.name('Table2');
ofQbds.addLink(fieldNum(Table1, Key), fieldNum(Table2, Key));
ofQbds.joinMode(JoinMode::InnerJoin);
range = strFmt('%1.%2 == %3 OR %4.%5 == %6', qbd.name(), 'A', '1',
ofQbds.name(), 'C', '5');
info(range);
ofQbds.addRange(fieldName2id(tableNum(Table1 ), 'A')).value(range);
qr = new QueryRun(q);
while (qr.next())
{
test = qr.get(test.TableId);
info(test.A + ','+test.Key);
}
info('done');
But the or condition does not work properly.
For example If I have values
Table1
A,Key
1,1
2,2
3,3
Table2
C,Key
2,2
I would expect 2 results from Table1
1,1
2,2
but I get only the first one
Message
Table1.A == 1 OR Table2.C == 2
2,2
done
I tried different joinModes and switching || and OR but nothing I tried yet works.
What I need to change to be able to have or condition in the code?
Try changing this line:
range = strFmt('%1.%2 == %3 OR %4.%5 == %6', qbd.name(), 'A', '1', ofQbds.name(), 'C', '5');
to
range = strFmt('((%1.%2 == %3) || (%4.%5 == %6))', qbd.name(), 'A', '1', ofQbds.name(), 'C', '5');
Don't use sql "or", instead use the x++ "||"
Edit: see http://www.axaptapedia.com/Expressions_in_query_ranges for more information.
Edit 2: This code executes for me in the desired fashion. I would recommend using the most up to date compile-time functions such as tableNum() and fieldNum() etc.
Query q;
QueryBuildDataSource qbd;
QueryBuildDataSource ofQbds;
QueryBuildRange qbr;
str range;
QueryRun qr;
CustTable custTable;
CustGroup custGroup;
q = new Query();
qbd = q.addDataSource(tableNum(CustTable));
ofQbds = qbd.addDataSource(tableNum(CustGroup));
ofQbds.addLink(fieldNum(CustTable, CustGroup), fieldNum(CustGroup, CustGroup));
ofQbds.joinMode(JoinMode::InnerJoin);
range = strFmt('((%1.%2 == %3) || (%4.%5 == %6))',
tableStr(CustTable),
fieldStr(CustTable, AccountNum),
'000001',
tableStr(CustGroup),
fieldStr(CustGroup, CustGroup),
'UAC');
info(range);
ofQbds.addRange(fieldNum(CustTable, AccountNum)).value(range);
qr = new QueryRun(q);
while (qr.next())
{
custTable = qr.get(tableNum(CustTable));
info(custTable.AccountNum + ',' +custTable.CustGroup);
}

How to create Query using IN?

I need to collect data and add it to temporary table in AX 2012 R3 using X++.
This is the Query on SQL
select store, receiptid, itemid, str(qty,16,0) as Qty, str(price,16,0) as Price, str(DISCAMOUNT,16,0) DiscAmount, str(taxamount,16,0) SalesTaxAmount ,convert(date, transdate) transdate, DATAAREAID from RETAILTRANSACTIONSALESTRANS
where DATAAREAID in ('5740','5760') and transdate >='2016-03-21' and transdate <='2016-03-27' and store in ('JTJDRN1','JNUSADP','JOFFICE')
and INVENTSTATUSSALES='2' and itemid in ('10010038') and receiptid in (select receiptid from RETAILTRANSACTIONPAYMENTTRANS where transdate >='2016-03-21' and transdate <='2016-03-27')
order by transdate
User can input transDate, itemid and storeid
this is what form looks like
this is my code so far
private void RetailPromoReport()
{
str receiptId, curDatetxt,fileLocation, filePath, itemtxt, startPtxt, endPtxt,
storetxt, item_txt, item2, receiptId2, rcptid_txt, store_txt, store2;
FileName fileName;
str 50 item, itemid, store;
container items, receiptid_con, stores;
int i,x, ware, itm, tot, y,z, rcptLen, storeLen;
Date emptyDate, startP, endP;
RetailTransactionPaymentTrans rtpt;
RetailTransactionSalesTrans rtst;
ReportRetailTemp rrpi_tmp, rrpi_tmp2;
QueryBuildRange qbr1, qbr2, qbr3, qbr4, qbr5;
QueryRun queryRun;
Query query, query2;
QueryBuildDataSource qbdsRetailTransactionPaymentTrans, qbdsRetailTransactionSalesTrans;
RecordInsertList recordILCRppi_tmp = new RecordInsertList(tableNum(ReportRetailTemp),false,false,false,false,false,rrpi_tmp);
;
startP = DateFrom.dateValue();
endP = DateTo.dateValue();
tot = 0;
delete_from rrpi_tmp;
while select receiptId from rtpt group by rtpt.receiptId where rtpt.transDate >= startP && rtpt.transDate <= endP
{
receiptid_con += rtpt.receiptId;
}
query = new Query();
qbdsRetailTransactionSalesTrans = query.addDataSource(tableNum(RetailTransactionSalesTrans));
qbr1 = qbdsRetailTransactionSalesTrans.addRange(fieldNum(RetailTransactionSalesTrans,TransDate));
qbr1.value(strfmt('(%3.transDate>=%1) && (%3.transDate<=%2)',Date2StrXpp(startP),Date2StrXpp(endP),qbdsRetailTransactionSalesTrans.name()));
qbr2 = qbdsRetailTransactionSalesTrans.addRange(fieldNum(RetailTransactionSalesTrans,inventStatusSales));
qbr2.value(queryValue(enum2str(RetailInventStatusSales::Posted)));
items = msCtrlCust.getSelectedFieldValues();
itemtxt = multilookupItem.valueStr();
stores = msCtrlStore.getSelectedFieldValues();
storetxt = multilookupStore.valueStr();
if(itemtxt != "")
{
item_txt = conPeek(items,1);
item2 = strFmt('(%2.itemId == "%1") ',queryValue(conPeek(items,1)),qbdsRetailTransactionSalesTrans.name());
itm = conlen(items);
if(itm > 1)
{
for (i = 2; i <= itm;i++)
{
item = conPeek(items,i);
item2 = strFmt('%1 || (%3.itemId == "%2") ',item2, queryValue(item),qbdsRetailTransactionSalesTrans.name());
}
}
qbr3 = qbdsRetailTransactionSalesTrans.addRange(fieldNum(RetailTransactionSalesTrans, itemId));
qbr3.value(strFmt("%1",item2));
}
rcptLen = conlen(receiptid_con);
receiptId2 = strFmt('(%2.receiptId == "%1") ',queryValue(conPeek(receiptid_con,1)),qbdsRetailTransactionSalesTrans.name());
if(rcptLen > 1)
{
for (y = 2; y <= rcptLen; y++)
{
rcptid_txt = conPeek(receiptid_con,y);
receiptId2 = strFmt('%1 || (%3.receiptId == "%2") ',receiptId2, queryValue(rcptid_txt),qbdsRetailTransactionSalesTrans.name());
}
}
qbr4 = qbdsRetailTransactionSalesTrans.addRange(fieldNum(RetailTransactionSalesTrans, receiptId));
qbr4.value(strFmt("%1",receiptId2));
if(storetxt != '')
{
store_txt = conPeek(stores,1);
store2 = strFmt('(%2.store == "%1") ',queryValue(conPeek(stores,1)),qbdsRetailTransactionSalesTrans.name());
storeLen = conlen(stores);
if(storeLen > 1)
{
for (z = 2; z <= storeLen;z++)
{
store = conPeek(stores,z);
store2 = strFmt('%1 || (%3.store == "%2") ',store2, queryValue(store),qbdsRetailTransactionSalesTrans.name());
}
}
qbr5 = qbdsRetailTransactionSalesTrans.addRange(fieldNum(RetailTransactionSalesTrans, store));
qbr5.value(strFmt("%1",store2));
}
qbdsRetailTransactionSalesTrans.addSortField(fieldNum(RetailTransactionSalesTrans, transDate),SortOrder::Ascending);
qbdsRetailTransactionSalesTrans.addSortField(fieldNum(RetailTransactionSalesTrans, itemId),SortOrder::Ascending);
queryRun = new QueryRun(query);
while (queryRun.next())
{
rtst = queryRun.getNo(1);
rrpi_tmp.store = rtst.store;
rrpi_tmp.receiptId = rtst.receiptId;
rrpi_tmp.itemId = rtst.itemId;
rrpi_tmp.qty = rtst.qty;
rrpi_tmp.price = rtst.price;
rrpi_tmp.discAmount = rtst.discAmount;
rrpi_tmp.SalestaxAmount = rtst.taxAmount;
rrpi_tmp.transDate = rtst.transDate;
recordILCRppi_tmp.add(rrpi_tmp);
tot++;
}
ttsBegin;
recordILCRppi_tmp.insertDatabase();
ttsCommit;
ReportRetailTemp_ds.research(true);
ReportRetailTemp_ds.refresh();
if(tot > 0)
{
Box::info(strFmt("%1 row data",tot));
}
else
{
Box::info(strFmt("No Data",tot));
}
}
My code doesn't show any error in short period but because receiptId is stored in str,
receiptId2 = strFmt('%1 || (%3.receiptId == "%2") ',receiptId2, queryValue(rcptid_txt),qbdsRetailTransactionSalesTrans.name());
there is limitation and show error for long periode
Can someone make my code more efficient and
is there any way to create Query in x++ that have same function like "IN" on SQL
You have two options:
You can use more than one query range for the same field; it will automatically count as an or
for (i = conLen(items); i > 0; i--)
qbdsRetailTransactionSalesTrans.addRange(fieldNum(RetailTransactionSalesTrans, itemId)).value(queryValue(conPeek(items,i)));
You may need special handling, if the container is empty!
Often it is better to use an (exists) join instead
ds = qbdsRetailTransactionSalesTrans.addDatasource(tableNum(RetailTransactionPaymentTrans));
ds.joinMode(JoinMode::ExistsJoin);
ds.relations(true); // Or do ds.addLink(...) etc.
I am not sure I follow the correct logic here :)
If you need to do crosscompany selections, do so using the interface for that:
qbdsRetailTransactionSalesTrans.allowCrossCompany(true);
qbdsRetailTransactionSalesTrans.addCompanyRange('5740');
qbdsRetailTransactionSalesTrans.addCompanyRange('5760');

Import Items into Ax with X++ Code

I was importing items into Microsoft Dynamics AX 2009 using the following job
static void ItemsImport(Args _args)
{
InventTable InventTable;
container c;
TextIo io;
str 130 fileName;
TextBuffer b;
integer inc;
ItemId ItemId;
AxInventTable axInventTable;
;
fileName = #"C:\Users\mom\Desktop\Items.csv";
b = new Textbuffer();
io = SysLicenseCodeReadFile::openFile(fileName,'r');
if (!io)
throw error(strfmt("#SYS18678",fileName));
io.inFieldDelimiter(";");
c = io.read();
b = new Textbuffer();
ttsbegin;
while (io.status() == IO_Status::Ok)
{
c = io.read();
inc++;
if (io.status() != IO_Status::Ok)
break;
ItemId = conpeek(c,1);
select InventTable
where InventTable.ItemId == ItemId;
axInventTable = new axInventTable();
axInventTable.parmItemId(conPeek(c, 1));
axInventTable.parmItemName(conPeek(c, 2));
axInventTable.parmNameAlias(conPeek(c, 3));
axInventTable.parmItemGroupId("PRD_CHF");
axInventTable.parmModelGroupId("PMP");
axInventTable.parmDimGroupId("Teinture");
axInventTable.axInventTableModule_Sales().parmUnitId("Kg");
axInventTable.axInventTableModule_Purch().parmUnitId("Kg");
axInventTable.axInventTableModule_Invent().parmUnitId("Kg");
axInventTable.parmBOMUnitId("g");
axInventTable.axInventItemInventSetup().axInventDim().parmInventSiteId("FIMA");
axInventTable.axInventItemPurchSetup().axInventDim().parmInventSiteId("FIMA");
axInventTable.axInventItemInventSetup().axInventDim().parmInventSiteId("FIMA");
axInventTable.axInventItemInventSetup().axInventDim().parmInventLocationId("MG_PRD_CHI");
axInventTable.axInventItemPurchSetup().axInventDim().parmInventLocationId("MG_PRD_CHI");
axInventTable.axInventItemInventSetup().axInventDim().parmInventLocationId("MG_PRD_CHI");
axInventTable.save();
}
ttscommit;
pause;
}
The records are created correctly in the table but when I open the default orders settings/Site specific order settings order form for the product,
all fields are still greyed out as if no records exists.
http://www.hostingpics.net/viewer.php?id=756928801.png
http://www.hostingpics.net/viewer.php?id=553431712.png
Has anybody faced this problem ? how I can correct the x ++ code ?
Any help would be appreciated.
Thanks,
You most likely need to change this line:
axInventTable = new axInventTable();
to this line:
axInventTable = axInventTable::newInventTable(inventTable);
This worked for me:
static void updateInventOrderSettings(Args _args)
{
InventTable inventTable;
InventItemInventSetup inventItemInventSetup;
InventItemPurchSetup inventItemPurchSetup;
InventItemSalesSetup inventItemSalesSetup;
InventDim inventDim;
;
ttsBegin;
inventTable = InventTable::find("00001", true);
inventTable.ItemGroupId = "Planning";
//.. other inventTable fields
inventTable.update();
inventDim.initValue();
inventDim.InventSiteId = "Site2";
inventDim.inventLocationId = "ARC";
inventDim = InventDim::findOrCreate(inventDim);
//Site specific setup
inventItemInventSetup.initValue();
inventItemInventSetup.InventDimId = inventDim.inventDimId;
inventItemInventSetup.ItemId = inventTable.ItemId;
inventItemInventSetup.insert();
inventItemPurchSetup.initValue();
inventItemPurchSetup.InventDimId = inventDim.inventDimId;
inventItemPurchSetup.ItemId = inventTable.ItemId;
inventItemPurchSetup.insert();
inventItemSalesSetup.initValue();
inventItemSalesSetup.InventDimId = inventDim.inventDimId;
inventItemSalesSetup.ItemId = inventTable.ItemId;
inventItemSalesSetup.insert();
//Default order settings
inventItemInventSetup= inventItemInventSetup::findDefault(inventTable.itemId, true);
inventItemInventSetup.InventDimIdDefault = inventDim.inventDimId;
inventItemInventSetup.update();
inventItemPurchSetup = inventItemInventSetup::findDefault(inventTable.itemId, true);
inventItemPurchSetup.InventDimIdDefault = inventDim.inventDimId;
inventItemPurchSetup.update();
inventItemSalesSetup= inventItemInventSetup::findDefault(inventTable.itemId, true);
inventItemSalesSetup.InventDimIdDefault = inventDim.inventDimId;
inventItemSalesSetup.update();
ttsCommit;
}

When calling stored procedure, .hasRows keeps staying "false"

I have a stored procedure which I am calling which will return data from a table.
But when I try to populate an .aspx with the data it skips my method from doing it because my method is based on whether a reader detects rows.
Here is my method:
private void editExhibit(int expenseID)//new
{
saveExhibitBtn.Text = "Update Exhibit";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["OSCIDConnectionString"].ToString());
SqlCommand cmd = new SqlCommand("p_CaseFiles_Exhibits_RetrieveExhibitDetails", conn);
cmd.CommandType = CommandType.StoredProcedure;
//cmd.Parameters.AddWithValue("#ExhibitID", expenseID);
cmd.Parameters.Add(new SqlParameter("#ExhibitID", SqlDbType.Int));
cmd.Parameters["#ExhibitID"].Value = expenseID;
bool hasAttachments = false;
string investigatorID = "";
//bool alreadyInvoiced = false;
bool isExpenseOwner = false;
string fileID = "-1";
try
{
conn.Open();
var reader = cmd.ExecuteReader();
if (reader.HasRows)//////////////////////craps out here bcause hasRows is false....
{
reader.Read();
fileID = reader["FileID"].ToString();
ddlCaseFiles.SelectedValue = fileID;
ddlCaseFiles.Enabled = false;
// retrieve exhibit details here
hasAttachments = (bool)reader["HasAttachments"];
investigatorID = reader["InvestigatorID"].ToString();
if (Session["InvestigatorID"].ToString() == investigatorID)
{
isExpenseOwner = true;
}
txtDateReceived.Value = reader["SeizeDate"].ToString();
ddlReceivedBy.SelectedValue = reader["SeizedByInvestigatorID"].ToString();
txtTimeReceived.Value = reader["SeizeTime"].ToString();
txtWhyHowReceived.Value = reader["SeizeAuthority"].ToString();
txtReceivedLocation.Value = reader["SeizeLocation"].ToString();
txtOurItemNum.Value = reader["NewExhibitOutItemNumber"].ToString();////////////
txtTheirItemNum.Value = reader["ClientItemNum"].ToString();
txtBagNum.Value = reader["BagNumber"].ToString();
txtBoxNum.Value = reader["BoxNumber"].ToString();
txtComment.Value = reader["ExhibitDecriptionPlainText"].ToString();
}
}
catch (SqlException ex)
{
ErrorLogger.Log(ex.Number, "NewExhibit.aspx - editExhibit - Retrieve Details", ex.Message);
}
Here is my stored procedure:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[p_CaseFiles_Exhibits_RetrieveExhibitDetails]
#FilterField nvarchar(max)=null
, #FilterQuery nvarchar(max)=null
, #SortName nvarchar(max)='SeizeDate, SeizeTime '
, #SortOrder nvarchar(max)='desc'
, #ExhibitID int
as
SET CONCAT_NULL_YIELDS_NULL OFF
declare #Command nvarchar(max)
Select #Command = 'select E.ExhibitID,convert(nvarchar,SeizeDate,111) as ''SeizeDate'',SeizeTime,ExhDesc,E.InvestigatorID as ''EnteredBy''
,E.SeizedByInvestigatoID as ''SeizedBy'',SBI.ActiveInvestigator, SBI.FName+'' '' + SBI.LName as ''SeizedByName'', E.FileID,[FileName]
,Investigators.FName,Investigators.LName,SzAuthority,Location,ItemID,SubItemID1,SubItemID2,SubItemID3,PageSerial,ClientItemNum,Privileged
,Private,E.HasAttachments,ItemEntryGradeID,BagNumber,BoxNumber,PL.PropertyId,P.PropertyTypeID,P.PropertyMakeID,P.PropertyModelID,SerialNumber,ColorID
,cast(ItemID as varchar)+''-''+cast(SubItemID1 as varchar)+''-''+cast(SubItemID2 as varchar)+''-''+cast(SubItemID3 as varchar) as ''ItemNumber'',StoredLocally
from CaseFileExhibits E
join Investigators on E.InvestigatorID = Investigators.InvestigatorID
join Investigators SBI on SBI.InvestigatorID=E.SeizedByInvestigatoID
join CaseFiles on E.FileID = CaseFiles.FileID
left join CaseFileExhibitPropertyLink PL on E.ExhibitID=PL.ExhibitID
left join Element09a_Properties P on P.PropertyID=PL.PropertyId
left join ElementPropertyTypes PT on PT.PropertyTypeID=P.PropertyTypeID
left join ElementPropertyMakes PM on PM.PropertyMakeID=P.PropertyMakeID
left join ElementPropertyModels PMD on PMD.PropertyModelID=P.PropertyModelID
where E.ExhibitID='+convert(nvarchar,#ExhibitID);
if(#FilterQuery is not null)
begin
select #Command+=' and '+#FilterField+ ' like '''+#FilterQuery+''' ';
end
select #Command+=' order by '+#SortName+' '+#SortOrder
So according to the stored procedure I only need to pass in the exhibitID, which I did.
Your Stored procedure looks incomplete. You probably need to add
exec sp_executesql #command;
At the end to get it to return your rows.
info about sp_executesql can be found at http://msdn.microsoft.com/en-us/library/ms188001.aspx

Resources