I have a dataview which binds to a PagedDataSource object. The data is pulled into the dataview from the db using a stored procedure and the returned data is sorted according to a date field. The stored proc is used in several places in the application and so I cant make any big change in this instance. I just need to disable the sort order which is returned by the stored proc (Without making any change to the stored proc) and apply a new sort.
objPagedDs = New PagedDataSource()
dvFeedback = objCompany.PublishedMonitoringCards.DefaultView
dvFeedback.RowFilter = "EligibleForPrinting = 1"
dvFeedback.Sort = "IncludeInRepReport DESC, Work_dt DESC"
Please find the code above.
I have 0,1,and null values in the database. It sorts Includeinreport in descending order. That means it sorts in the order of 1,0, and null. Apparently I want the null to be 0 when it returns from the database to make the sort working the way I want. Used ISNULL to do it. Doesnt relate to question but this what I did. The above code snippet is fine.
Related
I am writing a code that calls a column from a dataset using a SQL query. I use two parameters to identify which rows to select. One is the ProductSerialNumber, and the other is a datetimestamp. See my SQL query below
Select TestStation FROM tblData
WHERE ProductSerialNumber = ? AND Datetimestamp = ?
In the dataset's datatable the productserialnumber is formatted as text, and the other is formatted as a date (as you would expect).
In my vb.net code, I grab the Datetimestamp from another source (don't ask why, the only thing you need to know is that it grabs a valid datetimestamp, dimensioned as a date, that matches exactly with the tblData's entry) and I use the premade query to generate a datatable. The query is a Fill query called "TestStationLookUp"
my vb.net code looks like this
Dim dt as new dataset.tbldataDataTable
Dim dta As New DataSetTableAdapters.tbldataTableAdapter
Dim ProductSerialNumber as string = "XXXXXX"
Dim DateTimeStamp as date = SomeDateVariable
dta.TestStationLookUp(dt, ProductSerialNumber, DateTimeStamp)
It is here that the code tells me:
Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.
Line 7366: dataTable.Clear
Line 7367: End If
Error: Line 7368: Dim returnValue As Integer = Me.Adapter.Fill(dataTable)
Line 7369: Return returnValue
Line 7370: End Function
I cannot understand why this error arises, as everything is dimensioned the way it should be. This exact code setup works elsewhere in my code (except it doesn't use a date), but this specific piece won't work.
Also, if I go to the dataset in my solution, I can use the "preview data" on this query and type in the EXACT same parameters (the ProductSerialNumber and DateTimeStamp that match the record in the table AND what I use in my vb code) and it will give me produce the table I want.
Can anyone assist?
This error means that you are trying to access not valid unique id "ProductSerialNumber", maybe it does not exist
Failed to enable constraints. One or more rows contain values
violating non-null, unique, or foreign-key constraints.
Instead of passing the variable that comes from dataset ,pass a valid number that you are sure it exists in database
I'm trying to get the list of field names for a given table, to turn them into a string which I can to post back as a variable to another function.
I've Googled loads of stuff regarding GetSchemaTable but all I seem to be able to output are field parameters, but not the actual value of these parameters (ie ColumnName, which is the one I actually want!)
Found this page; What is the SQL command to return the field names of a table?
But all the queries on there give me an error "You do not have access to Table 'Columns'"
I feel sure this is pretty simple, can someone give me a little function that will simply give me
fieldNames = "fieldName1, fieldName2, etc"
I am using a MySQL server and ODBC connections ASP.NET using VB.
I don't know if this will work, but give it a try.
Instantiate a OdbcCommand with something like select * from yourtable limit 0;
Load a DataTable with the datareader returned from cmd.ExecuteReader.
DataTable dt as new DataTable()
dt.Load(cmd.ExecuteReader())
Now iterate through the columns of dt to find out what the column names are.
This is just and idea. Don't know if it will work or not.
So, my SQL Server admin has given me access to a stored procedure with 5 parameters that returns 15 columns of data.
However, if I want to filter on the columns that are not parametrized, I have just a few options. Creating a DataSet does not help, since the query to the database can only be the stored proc and it's parameters, not Select statements.
I can create an XML file and query that using Linq-to-XML
I can create some temporary tables in another database and query those
What am I missing?
some ideas...
1) Can you ask your dba for a new stored procedure that filters (using additional parameters) on columns you need to filter on?
2) Can you write your own stored procedures? If so, you could, for example declare a table variable, insert into it using an exec on the stored procedure your dba wrote, and then select from it using any filters you like.
3) re: your two options -- those will work -- you can pull all of the data into a datatable in asp.net, or an xml file, but that's moving and exposing data you know at design time you won't need, so not an ideal solution.
4) Can you directly query the table(s) yourself?
EDIT
You can bring (all) of the data into a datatable (asp.net), and then filter it there. For example (VB):
Dim myFilter as String
myFilter = "SomeField = SomeValue"
Dim myRows() as datarow
myRows = myDataSet.Tables(i).Select(myFilter)
For each myRow as datarow in myRows
myNewDataTable.ImportRow(myRow)
Next
It's not ideal, but considering the limitations...
Creating a DataSet does not help, since the query to the database can
only be the stored proc and it's parameters, not Select statements.
A DataSet can be filled using a stored procedure. When you filled up your DataSet then you filter the records using whatever data access technology you know/like.
marc_s is right, get a new DBA. If he doesn't want to create a stored procedure or add parameters to the existing procedure then he probably won't mind your application getting 1,700 records every time you call that stored procedure when all you really need is a subset of those records.
You can bring the data back into a DataSet and then use a DataView object to apply a filter. In short, this will call the stored procedure, gather all of the rows into the DataSet, and then the DataView will let you enumerate the data skipping over rows that don't match the filter.
Here's an example in C#: C# DataView Usage
If the number of records you get back is not huge, you could do this:
Create a POCO class to represent the data record coming back from the stored proc:
public class MyRecord
{
Field1Name { get; set;}
...
Field10Name { get; set;}
}
Populate a List<MyRecord> with the results coming back from your stored proc:
List<MyRecord> mylist = new List<MyRecord>();
foreach(record in collectionOfRecordsFromStoredProc)
{
mylist.Add(new MyRecord {
Field1Name = "", /* retrieve your value from record here */
...
Field10Name = "" /* retrieve your value from record here */
});
}
Then you can query those results using the standard Linq to Objects:
List<MyRecord> filteredRecords = mylist.Where(x => x.Field10Name.Contains("Smith")).ToList();
This essentially will do everything in memory without an intermediaray place to persist the data. But this will not scale well if you are expecting to receive very large numbers or records back from this stored proc.
NOTE: code above is untested so will probably need tweaking
SQL Tables
Listing
ID, Title.....
ListingType
ID, Name
ListingMatrix
ListingID, ListingTypeID
Basically a listing can be more than 1 type and I want that to be able to be shown using the ListingMatrix table. However, I'm having a lot of issues populating the checkboxlist because I have it being sorted by Title to keep it user friendly. I'm using VB.Net, LINQ and MS SQL.
Dim readListingMatrix = (From ListingCategories In db.ListingTypeMatrixes _
Where ListingCategories.ListingID = ListingID)
For Each row In readListingMatrix
CheckBoxListListingCategories.Items(row.ListingTypeID - 1).Selected = True
Next
My issue is storing the checklistbox and editing it. Storing I think I could hack, but editing it is becoming a pain since I can't get the checkboxlist to check the correct boxes since their location changes due to the ORDER BY in my SQL Statement that populates the list.
Assuming that the value field of your checkboxes is filled with a ListingTypeID, do this:
Dim readListingMatrix = (From ListingCategories In db.ListingTypeMatrixes _
Where ListingCategories.ListingID = ListingID)
For Each row In readListingMatrix
CheckBoxListListingCategories.Items.FindByValue(row.ListingTypeID).Selected = True
Next
I cannot find an elegant way to get the return value from a stored procedure when using TableAdapters.
It appears the TableAdapter does not support SQL stored procedure return values when using a non-scalar stored procedure call. You'd expect the return value from the auto-generated function would be the return value from the stored procedure but it isn't (it is actually the number of rows affected). Although possible to use 'out' parameters and pass a variable as a ref to the auto generated functions it isn't a very clean solution.
I have seen some ugly hacks on the web to solve this, but no decent solution. Any help would be appreciated.
http://blogs.msdn.com/smartclientdata/archive/2006/08/09/693113.aspx
The way to get the return value is to use a SqlParameter on the SqlCommand object which has its Direction set to ParameterDirection.ReturnValue. You should check the SelectCommand property of the TableAdapter after calling Fill.
NOTE: The way to go is using a SqlParameter where the Direction = ParameterDirection.ReturnValue
With that said, as someone already mentioned SqlParameters, here is a dynamic method alternate using a DataSet. (if thats how you ride):
Example SQL statement and C# as fallows:
string sql = #"DECLARE #ret int
EXEC #ret = SP_DoStuff 'parm1', 'parm2'
SELECT #ret as ret";
DataSet ds = GetDatasetFromSQL(sql); //your sql to dataset code here...
int resultCode = -1;
int.TryParse(ds.Tables[ds.Tables.Count-1].Rows[0][0].ToString(), out resultCode);
The stored procedure results are loaded into a DataSet and will have as many DataTables as return select statements in the stored procedure.
The last DataTable in the DataSet will have 1 row and 1 column that will contain the stored procedure return value.
I cannot say for certain because I have do not use TableAdapters, but you might need to look at your stored procedure and include the following around your procedure.
SET ROWCOUNT OFF
BEGIN
<Procedure Content>
END
SET ROWCOUNT ON
Closing this question as it appears return values aren't supported and there is no elegant workaround!
Actually, all you need to do is to return your final value from the stored procedure using a SELECT statement, not a RETURN statement. The result of the SELECT will be the return value. For example, if you simply make your sp exit statement "SELECT 1" then you'll get back a 1. Now just SELECT the actual scalar you want returned.