Programmatic Use Of SQLDataSource Not Returning Dataview
Sep 4, 2007
I am creating an ad-hoc reporting module for my website. The user may select a list of columns and specify the WHERE for the report. I build the select statement and the where statement and pass the info to a stored procedure. The stored procedure accepts 3 select parameters and a 3 wherestmt parameters. I finally got the SQLDatasource to work by setting the parameter values in the Selecting method of the SQLDatasource. Binding it to a gridview shows me all my values. Now, I am trying to programmatically call the select method of the SQLDatasource so I can get a dataview or datareader to manipulate further. I am getting an null back when I call the select method. Any ideas why? or a workaround?
<VB Code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Getting an error that the object is null? why is the above code not returning any data?
'Tried using a datareader and datasource.Dim rptview As IDataReader = CType(SqlDataSource1.Select(DataSourceSelectArguments.Empty), IDataReader)
If rptview.Read Then
lblMsg.Text = "Got Rows"
End If
End Sub
Protected Sub SqlDataSource1_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs) Handles SqlDataSource1.Selecting
'For this sp, need to set each paramater even if it is not being used. Setting it in the wizard
Hi, Is there a way to programmatically access the results of an SQLDataSource control select at the time it is binding to a DetailView? There are some fields in the data results I do not want to render to the page, but I still need for other stuff. I know I can programmatically invoke a select method, but since it is selecting anyway for binding to the DetailView it would be better to get all the data in one swoop. Thanks in advance for any assistance you could provide. Best Regards, Brett
Hi all, In my VWD 2005 Express, I created a website "AverageTCE" that had Default.aspx, Default.aspx.vb and App_Code (see the attached code) for configurating a direct SqlDataSource connection to the dbo.Table "LabData" of my SQL Server 2005 Express "SQLEXPRESS" via SqlDataSource, DataView, CType Function and the Page_Load procedure. I executed the website "AverageTCE" and I got Compilation ErrorBC30451: Name 'SqlDataSource3' is not declared:
Server Error in '/AverageTCE' Application.
Compilation Error Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. Compiler Error Message: BC30451: Name 'SqlDataSource3' is not declared.Source Error:
Line 8: <DataObjectMethod(DataObjectMethodType.Select)> _ Line 9: Public Shared Function SelectedConcentration() As ConcDB Line 10: Dim dv As DataView = CType(SqlDataSource3.Select(DataSourceSelectArguments.Empty), DataView) Line 11: dvConcDB.RowFilter = "Concentration = '" & ddlLabData.SelectedValue & "'" Line 12: Source File: C:Documents and Settingse1enxshcMy DocumentsVisual Studio 2005WebSitesAverageTCEApp_CodeConcDB.vb Line: 10 //////////--Default.aspx--////////////////////////// <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>SQL DataSource</title> </head> <body> <form id="form1" runat="server">
</div> </form> </body> </html> ///////////--Default.aspx.vb--//////////////////////////////// Partial Class _Default Inherits System.Web.UI.Page End Class ////////////////--App_Code/ConcDB.vb--////////////////////// Imports Microsoft.VisualBasic Imports System.ComponentModel Imports System.Data Imports System.Data.SqlClient Imports System.Data.SqlTypes <DataObject(True)> Public Class ConcDB <DataObjectMethod(DataObjectMethodType.Select)> _ Public Shared Function SelectedConcentration() As ConcDB Dim dv As DataView = CType(SqlDataSource3.Select(DataSourceSelectArguments.Empty), DataView) dvConcDB.RowFilter = "Concentration = '" & ddlLabData.SelectedValue & "'" Dim dvRow As DataRowView = dvConcDB(0) Dim ConcDB As New ConcDB ConcDB.SelectedConcentration = CDec(0)("Concentration") Return ConcDB End Function Call AverageValue (Conc1) Public Shared Function AverageValue(ByVal Conc1 As Decimal) Dim AverageConc As Decimal AverageConc = (Conc1 + 22.0) / 2 Return AverageConc End Function End Class ************************************************************** I have 2 questions to ask: 1) How can I fix this Compilation Error BC30451: Name 'SqlDataSource3' is not declared? 2) I just read MSDN Visual Studio 2005 Technical Article "Data Access in ASP.NET 2.0" and I saw the following thing: Types of Data Sources: SqlDataSouirce: The configuration of a SqlDataSoure is more complex then that of the AccessDataSource, and is intended for enterprise applications that require the features provided by a true database management system (DBMS). I am using the website application in VWD 2005 Express to do the task of extracting data values from the Tables of SQL Server 2005 Express via .NET Framwork, ASP.NET 2.0 and VB 2005 programming. Can VWD 2005 Express be configured to SQL Server 2005 Express (SQLEXPESS) for the SqlDataSource connection and do the data-extraction task via DataView, CType Function and the Page-Load procedure? Please help, respond and answer the above-mentiopned 2 questions. Many Thanks, Scott Chang
I am trying to put the data from a field in my database into a row in a table using the SQLDataSource.Select statement. I am using the following code: FileBase.SelectCommand = "SELECT Username FROM Files WHERE Filename = '" & myFileInfo.FullName & "'" myDataRow("Username") = CType(FileBase.Select(New DataSourceSelectArguments()), String)But when I run the code, I get the following error:Server Error in '/YorZap' Application. Unable to cast object of type 'System.Data.DataView' to type 'System.String'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidCastException: Unable to cast object of type 'System.Data.DataView' to type 'System.String'.Source Error: Line 54: FileBase.SelectCommand = "SELECT Username FROM Files WHERE Filename = '" & myFileInfo.FullName & "'" Line 55: 'myDataRow("Username") = CType(FileBase.Select(New DataSourceSelectArguments).GetEnumerator.Current, String) Line 56: myDataRow("Username") = CType(FileBase.Select(New DataSourceSelectArguments()), String) Line 57: Line 58: filesTable.Rows.Add(myDataRow)Source File: D:YorZapdir_list_sort.aspx Line: 56 Stack Trace: [InvalidCastException: Unable to cast object of type 'System.Data.DataView' to type 'System.String'.] ASP.dir_list_sort_aspx.BindFileDataToGrid(String strSortField) in D:YorZapdir_list_sort.aspx:56 ASP.dir_list_sort_aspx.Page_Load(Object sender, EventArgs e) in D:YorZapdir_list_sort.aspx:7 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +13 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +45 System.Web.UI.Control.OnLoad(EventArgs e) +80 System.Web.UI.Control.LoadRecursive() +49 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3743 Version Information: Microsoft .NET Framework Version:2.0.50727.42; ASP.NET Version:2.0.50727.210 Please help me!
Hello all,I have a sqldatasource that inserts data to the database but I want to get the ID from an Identity field after I am done inserting the data. How can I best do that? I'm not using a stored procedure to do this. <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:onepduConnectionString %>" InsertCommand="INSERT INTO [tblaccounts] ([fname],[lname], [address], [city], [state], [zip], ,[phone],[credits]) VALUES (@fName,@lname, @address, @city, @state, @zip, @email, @phone, @credits)> <InsertParameters> <asp:FormParameter Name="fname" FormField="FirstNameTextBox" Type="String" /> <asp:FormParameter Name="lname" FormField="LastNameTextBox" Type="String" /> <asp:FormParameter Name="address" FormField="AddressTextBox" Type="String" /> <asp:FormParameter FormField="cityTextBox" Name="city" Type="String" /> <asp:FormParameter FormField="stateTextBox" Name="state" Type="String" /> <asp:FormParameter FormField="zipTextBox" Name="zip" Type="String" /> <asp:FormParameter FormField="emailTextBox" Name="email" Type="string" /> <asp:FormParameter FormField="phoneTextBox" Name="phone" Type="string" /> <asp:Parameter Name="credits" DefaultValue=0 /> </InsertParameters> </asp:SqlDataSource>
TotalSelected.Value = SqlDataSource1.SelectCommand = "SELECT COUNT(*) FROM tblNews";
the reason i am tring to do this is so if i can find out the amount of rows before sqldatasource selects for details view then i can make the sqldataesource select depends on total minus 5 so e.g. if total 200 then - 5 so i can select bottom 195 so it misses top 5 for details view any1 any ideas? Thanks Andy,
Hi, Hope you guys won't mind this rather newbie question. I'm writing a simple blog page for my website and have created a SqlDataSource which queries the database for a list of blog post titles (from the web.Blog table) and the number of comments (from the web.BlogComments table). The SqlDataSource control is: <asp:SqlDataSource ID="sourceBlogArticles" ProviderName="System.Data.SqlClient" connectionString="<%$ ConnectionStrings:myDatabase %>" runat="server" SelectCommand="SELECT gb.blogID, gb.title, gb.description, gb.tags, gb.dateAdded, COUNT(gbc.blogID) AS noOfComments FROM web.Blog gb LEFT OUTER JOIN web.BlogComments gbc ON gb.blogID = gbc.blogID GROUP BY gb.blogID, gb.title, gb.description, gb.tags, gb.dateAdded ORDER BY gb.dateAdded"></asp:SqlDataSource> This works perfectly well if each blog entry in the web.Blog table has associated comments in the web.BlogComments table. However, if there are no comments yet defined in the web.BlogComments table for that blogID then no row is returned in ASP.Net (as checked with a GridView control or similar linked to the data source to view what I get) HOWEVER, I think the SELECT command IS correct: if I use the select command as a query in SQL Server Managment Studio Express, I do get the rows returned, with 0 for the number of comments which is what I would expect for that query: blogID, title, description, tags, dateAdded, noOfComments 1, title 1, description for title 1, tag1, 2007-09-27 06:49:03.810, 32, title 2, description for title 2, tag2, 2007-09-27 06:49:37.513, 03, title 3, description for title3, tag3, 2007-10-02 18:21:30.467, 0 Can anyone help? The result from the SSMSE query is what I want, yet when I use the very same SELECT statement in my SqlDataSource I don't get any rows returned if the BlogComment count is zero (in the above example I get only the first row). Many thanks for any suggestions!
Hi, and thanks in advance. I have VWD 2005 Express and SQL 2005 Express running. I have a SqlDastasource wired to the stored procedure. When I only include one Control parameter I get results from my Stored procedure, when I inclube both Control Parameters I get no results. I manually remove the second control parameter from the sqldatasource by deleting... <asp:ControlParameter ControlID="ddlSClosed" DefaultValue="" Name="SClosed" PropertyName="SelectedValue" Type="String" /> I have one Radio Group and one dropdownlist box that supplies the parameters. The dropdownlist parameter is Null or "" when the page is first loaded. Below is my SQLDatasource and Stored procedure. I am new to Stored Procedures, so be gentle. Any help would be appreciated!
ALTER PROCEDURE [dbo].[spDisplayServiceOrders] ( @SDate_Entered SmallDateTime, @SClosed nvarchar(50)= NULL ) AS If @SClosed IS NULL BEGIN
SELECT Service_Orders.SStore_Assigned_Number, Store_Info.Store_Other, Service_Orders.PO_Number, Service_Orders.SWorkType, Service_Orders.Service_Order_Number, Service_Orders.SDate_Entered, Service_Orders.SContact, Service_Orders.SClosed FROM Service_Orders INNER JOIN Store_Info ON Service_Orders.Store_ID = Store_Info.Store_ID and SDate_Entered >= @SDate_Entered Order by SDate_Entered DESC END ELSE BEGIN
SELECT Service_Orders.SStore_Assigned_Number, Store_Info.Store_Other, Service_Orders.PO_Number, Service_Orders.SWorkType, Service_Orders.Service_Order_Number, Service_Orders.SDate_Entered, Service_Orders.SContact, Service_Orders.SClosed FROM Service_Orders INNER JOIN Store_Info ON Service_Orders.Store_ID = Store_Info.Store_ID and SDate_Entered >= @SDate_Entered and SClosed = @SClosed Order by SDate_Entered DESC
I have a page with over 20 Textbox and DDL controls and an upload in various Divs and Panels (Ajax enabled) that are used for gathering user data. Some of the fields are mandatory and some optional. In the Code behind (VB- I am a complete novice) On the submit button click event, I iterate through the controls in the page and build an array with information from the controls that have data in them, (filtering out the non-filled textboxes, and DDLs). All this works well, and I get an array called 'myInfo' with the columns with the control ID, and control values 'rvalue' (as string), with the number of rows equal to the filled textboxes and DDLs. I then step through the array and build a string with 'name=values' of all the rows in the myinfo array and email this as a message: ThisMessage = "" NoOfControls = myInfo.GetLength(0) For i = 0 To NoOfControls - 1 ThisMessage = ThisMessage & myInfo(i).ID.ToString & "=" & myInfo(i).rvalue.ToString & "; " Next SendMail(email address, ThisMessage) I also want to add this information to a database, appended by the IP address and datetime.now. Dim evdoDataSource As New SqlDataSource() evdoDataSource.ConnectionString = ConfigurationManager.ConnectionStrings("SQLConnectionStringCK").ToString evdoDataSource.InsertCommandType = SqlDataSourceCommandType.Text Dim InsertMessage As String = """INSERT INTO evdoData (" NoOfControls = myInfo.GetLength(0) Dim k As Integer For k = 0 To NoOfControls - 1 InsertMessage = InsertMessage & myInfo(k).ID.ToString & ", " Next InsertMessage = InsertMessage & "IPNo, DateEntered) VALUES (" For k = 0 To NoOfControls - 1 InsertMessage = InsertMessage & "@" & myInfo(k).ID.ToString & ", " Next InsertMessage = InsertMessage & ", @IPNo, @DateEntered" & ")""" evdoDataSource.InsertCommand = InsertMessage I then similarly iterate through and do the insertparameters. Now here is the rub- (My all too often DUH moment!) When I look at the insertmessage in debug (and to be sure- I also show the insert string on a temporary debug label on the page), The insertmessage looks fine: "INSERT INTO EvdData (FirstName, Age, Email, Phone, Country, City, IPNo, DateEntered) VALUES (@FirstName, @Age, @Email, @Phone, @Country, @City, , @IPNo, @DateEntered)" However when the above code(evdoDataSource.InsertCommand = InsertMessage) is run, I get an error - the message with the error is: The identifier that starts with 'INSERT INTO ModelData (FirstName, Age, Email, Phone, Country, City, IPNo, DateEntered) VALUES (@FirsteName, @Age, @Email, @Phone,' is too long. Maximum length is 128 EH? When I actually copy the InsertMessage from the debug window and paste it manually after the command "evdoDataSource.InsertCommand = " It works, and I get the data inserted into the table.. -It would seem that I am probably missing something obvious in my complete "noviceness" . HELP! (oh and thanks a bunch in anticipation) _____________________________________________________________________________________________________________________ Its Easy --------------------------When you know How. Meanwhile Aaaaaaaaah .
I need to set up a job to allow users to restore their databases, on SQL Server 2000 SP3. The idea is that a user inserts a record into a table, identifying the dump they want to load. (They can only restore their own account.) A job picks up this record, restores the database, and notifies the user as appropriate.
My part of this is writing the procedure that the job executes, including the dump restore. Part of that is getting each dump's file groups (data, index, and log) into the proper locations for this server and this user.
Essentially, I need to be able to access the results of 'load filelistonly' from a cursor. How do I access the file list?
I'm developing custom SSIS task (control flow component) which offers usert to choose ADO.NET connection.
I want to use this connection in my code and access SQL server.
There is no any problem unless connection is with IntegratedSecurity = true.
But, when user chooses to set username and password, I can not access password because it is not present in the connection string as sensitive information.
Package.DTSProtectionLevel is set to EncryptAllWithUserKey
I need to programmaticaly access to password, but I don't know which class to use from DTS (SSIS) object model.
I am trying building a package from code. I have been able to follow the SSIS samples and build my control flow with foreach loop and SQL Commands pretty easily.
The data flow has been a different story, I am struggling with input and output columns. I trying to read from a flatfile, convert data, perform a lookup, and update or insert based on the results of the lookup. I was able to build this package in the designer and it works just as I want, but I am having problems duplicating the data flow in the code.
I was able add the flatfile, data conversion, and insert controls on the data flow and linked them together. However, I cannot figure out how get the input columns in the data convert object to become selected and generate the converted output columns.
I have tried to refresh metadata and mappings column, but to no success. The only custom property for this component seems to be SourceInputColumnLineageId, but I cannot figure how to set it. Can someone give me nudge or push in the right direction?
// Get the design time instance of the component and initialize the component CManagedComponentWrapper instance = convert.Instantiate(); instance.ProvideComponentProperties();
// Reinitialize the metadata. instance.AcquireConnections(null); instance.ReinitializeMetaData(); instance.ReleaseConnections();
// Iterate through the inputs of the component. IDTSVirtualInput90 vInputLkUp = convert.InputCollection[0].GetVirtualInput(); foreach (IDTSVirtualInputColumn90 vColumn in vInputLkUp.VirtualInputColumnCollection) { IDTSInputColumn90 col = instance.SetUsageType(convert.InputCollection[0].ID, vInputLkUp, vColumn.LineageID, DTSUsageType.UT_READONLY); //instance.SetInputColumnProperty(convert.InputCollection[0].ID, col.ID, "SourceInputColumnLineageId", 1); }
Hello, I am using a sqldatareader to get back a whole set of data. The columns are id, data_id and data_desc for example, the collection is id data_id data_desc0 100 this is name for id 00 101 this is address for id 00 102 this is gender for id 01 100 this is name for id 11 101 this is address for id 11 102 this is gender for id 12 100 this is name for id 22 101 this is address for id 22 102 this is gender for id 23 100 this is name for id 33 101 this is address for id 33 102 this is gender for id 3 I want to be able to go thru' this list and break up for each id and create a txt file. So, i will have four text files. txt0.txt will contain100, this is name for id 0 101, this is address for id 0102, this is gender for id 0 I would like to know, how do i use a dataview to break up the sqldatareader so i can then repeat the loop for each id and generate the text file. I don't have a problem generating the text file. Please let me know, how should i go about it. Thanks a bunch,-Sean
I don't know if this topic should go in this forum category or in the SQLDataSource forum. I need to be able to provide SQL which varies based on what the user enters on a page. However, this isn't as simple a providing parameters in the SQLDataSource control because the SQL changes depending on what the user selects. For example, in a customer search page, they choose to search by either first name or last name from a drop down list and then enter the name to search for in a text box. The dataview should display the matching customers. How can I set this SQL based on the entered values while also keeping the paging and sorting capabilities of the dataview? You don't seem to be able to set the SQL for an SQLDataSource at run time.
In the dataview rowfilter property, how can I say that I just wantTitles that start with 'A' to 'J' ??ex:dv.rowfilter = " Country = ' France ' "I wantdv.rowfilter = " Title = (from 'A' to 'J') "This doesn't work :dv.rowfilter = " Title like '[a-j]%' "Neither does :dv.rowfilter = " Title like 'a%'" AND "Title like 'b%'" AND..so onBut this does work just for the Titles starting with 'a'dv.rowfilter = " Title like 'a%' "any idea ?JMT
I'm trying to create an SSIS package that will do a straight data copy between databases. The problem is that the underlying schema of the origin may change and the requirement is that the transfer be table driven. i.e. the tables that are copied are listed in a table and there should be no human intervention when the schema changes.
I'm moving data between SQL Server and SQL Azure, so backup and restore doesn't work. Has to be an SSIS package.
What's the best way to deal with a changing schema in an SSIS package? Can I delete and rewrite the underlying XML for any tables that change? Do I need to do it programmatically with C#? Do I need to create the package from scratch each time?
Hi, I use a filter on a dataview which has uniq rows. I need to bind several fields of the result filtered row to textboxes. Here the code : protected void Page_Load(object sender, EventArgs e) { string id = Request.QueryString["id"]; if (PreviousPage != null) { SqlDataSource dsPrev = (SqlDataSource)PreviousPage.FindControl("SqlDataSource1"); DataView dv = (DataView)(dsPrev.Select(DataSourceSelectArguments.Empty)); dv.RowFilter = "dr_id='" + id + "' "; dv.RowStateFilter = DataViewRowState.CurrentRows; txtFirstName.Text = // ??? FirstName Field txtLastName.Text= // ??? LastName Field txtAddress.Text= // ??? Address Field } } I don't know which cod to put in those lines. On the help of the dataView there is an example that use DataBindings. This example is in the DataView.RowFilter article: Text1.DataBindings.Add("Text",view,"CompanyName"); The big problem is that I don't have a method or event call 'DataBindings'. I just have 'DataBind' method or dataBinding event and they both don't support the 'Add' method. So how can I bound those controls to my filtered Dataview field value. Thanks, David
Question related to Visual Basic Video Lesson 09 (Databinding.wmv) by Bob Tabor.
Made a table and a UI form according to this lesson (table colums: CustomerID, FirstName, LastName).
Is it possible to use the same or an identical looking query form to find "Bob" by typing Bob in the Fist Name textbox or "Tabor" by typing Tabor in the Last Name textbox as in FileMaker?
Hi, I need to create filter which retrieves data for current moment. [time].[date].lastchild is not an option because the calender in database is generated till following year (2008).
I guess script goes like..
[time].[date].currentmember
but it does not work.
I'm green with these MDX scripts.. I'd be very pleased if some one of you gurus could help me.
I have the following SqlDataSource in my page:<asp:SqlDataSource ID="sqlds" runat="server" ConnectionString="<%$ ConnectionStrings:cs %>" SelectCommand="SELECT [Quest1], [Quest2], [Quest3], [Quest4], [Quest5] WHERE ([QuestID] = @QuestID)"> <SelectParameters> <asp:Parameter Name="QuestID" /> </SelectParameters> In my code I get the following error: "Cannot convert type 'int' to 'System.Data.DataView'", I don't understand why I am getting this error because I am casting my SqlDataSource as type DataView when passing it to my DataView type.Code: protected void Chart(string record) { System.Data.DataView dv = (System.Data.DataView)sqlds.SelectParameters.Add("QuestID", System.TypeCode.Int32, record); //Error line ... ... ...}If anyone could point me in the right direction I would be very grateful.
I need access to the underlying DataView associated with a declaratively defined SQLDataSource. Ideally, I need this access in the SQLDataSource's Selected event. I know that I can use the SQLDataSouce.Select() method to return the underlying DataView object. But, there is a GridView control bound to the datasource so I don't want to explicity call Select() since it will end up being called again implicity by the gridview itself. I have seen that this can be done with an ObjectDataSouce as follows: void odsDataSouce_Selected(object sender, ObjectDataSourceStatusEventArgs e) { DataView oDV = (DataView)e.ReturnValue;} Is there any way to accomplish the same thing with a SQLDataSouce? It seems hard to believe that the query results are not exposed to the Selected event. Thanks!
(Hope this isn't a "stupid" question, but I haven't been able to find a straight-forward answer anywhere)" I currently have code that iterates through a dataview's records, making a change to a field in some of the records. The way I have this coded, a conection has to opened & closed for each individual record that's updated: dsrcUserIae.UpdateCommand = "UPDATE UserIAE SET blnCorrect = @blnCorrect WHERE (ID = @ID)" dsrcUserIae.UpdateParameters.Add("blnCorrect", SqlDbType.Bit) dsrcUserIae.UpdateParameters.Add("ID", SqlDbType.Int) Dim myDataView As DataView = CType(dsrcUserIae.Select(DataSourceSelectArguments.Empty), DataView) For Each myRow As DataRowView In myDataView If myRow("FkUsersAnswerID") = myRow("AnswerID") Then intCorrect = 1 Else intCorrect = 0 End If dsrcUserIae.UpdateParameters.Item("blnCorrect").DefaultValue = intCorrect dsrcUserIae.UpdateParameters.Item("ID").DefaultValue = myRow("ID") intUpdateResult = dsrcUserIae.Update() Next It seems like I should be able to do something like this (call update once), but I'm not sure how... dsrcUserIae.UpdateCommand = "UPDATE UserIAE SET blnCorrect = @blnCorrect WHERE (ID = @ID)" dsrcUserIae.UpdateParameters.Add("blnCorrect", SqlDbType.Bit) dsrcUserIae.UpdateParameters.Add("ID", SqlDbType.Int) Dim myDataView As DataView = CType(dsrcUserIae.Select(DataSourceSelectArguments.Empty), DataView) For Each myRow As DataRowView In myDataView If myRow("FkUsersAnswerID") = myRow("AnswerID") Then myRow("blnCorrect") = 1 Else myRow("blnCorrect") = False End If Next intUpdateResult = dsrcUserIae.Update() 'Want all changed myRow("blnCorrect") to be updated to datasource Can anybody explain how to do the bulk update? I've seen some info about AcceptChanges and Merge, but I'm not sure if they apply here, or if they more for Transactions.
I have reviewed the BOL documentation on how to configure Peer-to-Peer replication via T-SQL and how to use the Replication Wizard to implement replication.
What I would like to find out is how do I configure the peer-to-peer replication process to use an existing column on a table that contains a GUID instead of creating an extra column with a uniqueidentifier GUID value. When you use the Wizard each table article has this extra column added to it.
I don't seem to be able to find it in the books-on-line. Can some one point me to the correct article or BOL page.
I am opening a simple command against a view which joins 2 tables, so that I can return a column which is defined as a tinyint in one of the tables. The SELECT looks like this: SELECT TreatmentStatus FROM vwReferralWithAdmissionDischarge WHERE ClientNumber = 138238 AND CaseNumber = 1 AND ProviderNumber = 89 The TreatmentStatus column is a tinyint. When I execute that above SQL SELECT statement in SQL Server Management Studio (I am using SQL Server 2005) I get a value of 2. But when I execute the same SQL SELECT statement as a part of a SqlDataReader and SqlCommand, I get a return data type of integer and a value of 1. Why?
What is the C# code I use to do this? I'm guessing it should be fairly simple, as there is only one row selected. I just need to pull out a specific field from that row and then insert that value into a different SqlDataSource.
I hvae a stored procedure that has this at the end of it: BEGIN EXEC @ActionID = ActionInsert '', @PackageID, @AnotherID, 0, '' END SET NOCOUNT OFF
SELECT Something FROM Something Joins….. Where Something = Something now, ActionInsert returns a Value, and has a SELECT @ActionID at the end of the stored procedure. What's happening, if that 2nd line that I pasted gets called, 2 result sets are being returned. How can I modify this SToredProcedure to stop returning the result set from ActionINsert?
i am using visual web developer 2005 with SQL Express 2005 with VB as the code behindi have one database and three tables in itfor manipulating each table i am using separate SqlDataSource() is it sufficient to use one SqlDataSource() for manipulating all the three tables ? i am manipulating all the tables in the same page only please help me
On cmd.ExecuteNonQuery(); I am getting the following error "Procedure or function usp_Question_Count has too many arguments specified."Any Ideas as to how to fix this. Oh and I will include the SP down at the bottom // Getting the Correct Answer from the Database. int QuiziD = Convert.ToInt32(Session["QuizID"]); int QuestionID = Convert.ToInt32(Session["QuestionID"]); SqlConnection oConn = new SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\quiz.mdf;Integrated Security=True;User Instance=True"); SqlCommand cmd = new SqlCommand("usp_Question_Count", oConn); cmd.CommandType = CommandType.StoredProcedure; SqlParameter QuizParam = new SqlParameter("@QuizId", SqlDbType.Int); QuizParam.Value = QuiziD; cmd.Parameters.Add(QuizParam); SqlParameter QuestionParam = new SqlParameter("@QuestionID", SqlDbType.Int); QuestionParam.Value = QuestionID; cmd.Parameters.Add(QuestionParam); SqlParameter countParam = new SqlParameter("@CorrectAnswer", SqlDbType.Int); countParam.Direction = ParameterDirection.Output; //cmd.Parameters.Add(workParam); cmd.Parameters.Add(countParam); oConn.Open(); cmd.ExecuteNonQuery(); // get the total number of products int iCorrectAnswer = Convert.ToInt32(cmd.Parameters["@CorrectAnswer"].Value); oConn.Close();Heres the stored ProcedureALTER PROCEDURE dbo.usp_Find_Correct_Answer @QuizID int, @QuestionID int, @CorrectAnswer int OUTPUT /* ( @parameter1 int = 5, @parameter2 datatype OUTPUT ) */AS /* SET NOCOUNT ON */ SELECT @CorrectAnswer=CorrectAnswer FROM Question WHERE QuizID=@QuizID AND QuestionOrder=@QuestionID
I have a web application that is data driven from a SQL 2005 database. The application needs to prompt the user to enter some information that will be logged into a SQL table. It should always be the last row in the table that is being worked on at any one time. Over a period the user will need to enter various fields. Once the data is entered into a field they will not have access to amend it. Therefore I need to be able to SELECT the last row of a table and present the data to the user with the 'next field' to be edited. As I'd like to do this as a stored procedure which can be called from an ASP page I wonder if anyoen might be able to help me with some T-SQL code that might achieve it? Regards Clive
I'm hoping someone can help me w/this query. I'm gathering data from two tables and what I need to return is the following: An employee who is not in the EmployeeEval table yet at all and any Employee in the EmployeeEval table whose Score column is NULL. I'm So lost PLEASE HELP. Below is what I have. CREATE PROCEDURE dbo.sp_Employee_GetEmployeeLNameFNameEmpID ( @deptID nvarchar(20), @Period int)ASSELECT e.LastName + ',' + e.FirstName + ' - ' + e.EmployeeID AS ListBoxText, e.EmployeeID, e.LastName + ',' + e.FirstName AS FullName, ev.Score FROM Employee AS eLEFT JOIN EmployeeEval as ev ON e.EmployeeID = ev.EmployeeIDWHERE e.DeptID = @deptId OR (e.deptid = @deptID AND ev.Score = null AND ev.PeriodID = @Period)GO
hello, I have a small problem. i'm adding records into the DB. the primary key is the company name which is abviously unique. before saving the record i check in the stored procedure if the company code is unique or not. if unique then the record is added & an output parameter is set to 2 & should b returned to the data access layer. if not unique then 3 should be returned. but everytime it seems to be returning 2 whether it is unique or not. can u plz help me? here is the code of the data access layer: cmd.Parameters.Add("@Status", SqlDbType.Int); cmd.Parameters["@Status"].Value = ParameterDirection.ReturnValue;
//cmd.UpdatedRowSource = UpdatedRowSource.OutputParameters; cmd.ExecuteNonQuery(); status = (int)cmd.Parameters["@Status"].Value;
here is the stored procedure: CREATE PROCEDURE spOrganizationAdd( @OrgCode varchar(10), @OrgName varchar(50), @AddressLine1 varchar(30), @AddressLine2 varchar(30), @City varchar(15), @State varchar(15), @Country varchar(15), @PinCode varchar(7), @Phone varchar(20), @Fax varchar(20), @Website varchar(30), @Email varchar(50), @CreatedBy int, @LastModifiedBy int, @Status INTEGER OUTPUT) AS BEGIN TRAN IF EXISTS(SELECT OrgCode FROM tblOrganizationMaster WHERE OrgCode = @OrgCode) BEGIN SET @Status = 3
END ELSE BEGIN INSERT INTO tblOrganizationMaster VALUES( @OrgCode, @OrgName, @AddressLine1 , @AddressLine2 , @City , @State, @Country, @PinCode, @Phone, @Fax , @Website, @Email, @CreatedBy , GETDATE(), @LastModifiedBy , GETDATE()) SET @Status = 2 END IF @@ERROR = 0 COMMIT TRAN ELSE ROLLBACK TRAN