Hi all, From the "How to Call a Parameterized Stored Procedure by Using ADO.NET and Visual Basic.NET" in http://support.microsft.com/kb/308049, I copied the following code to a project "pubsTestProc1.vb" of my VB 2005 Express Windows Application:
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.SqlDbType
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim PubsConn As SqlConnection = New SqlConnection("Data Source=.SQLEXPRESS;integrated security=sspi;" & "initial Catalog=pubs;")
Dim testCMD As SqlCommand = New SqlCommand("TestProcedure", PubsConn)
testCMD.CommandType = CommandType.StoredProcedure
Dim RetValue As SqlParameter = testCMD.Parameters.Add("RetValue", SqlDbType.Int)
Console.WriteLine("Number of Records: " & (NumTitles.Value))
End Sub
End Class
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// The original article uses the code statements in pink for the Console Applcation of VB.NET. I do not know how to print out the output of ("Book Titles for this Author:"), ("{0}", myReader.GetString(2)), ("Return Value: " & (RetValue.Value)) and ("Number of Records: " & (NumTitles.Value)) in the Windows Application Form1 of my VB 2005 Express. Please help and advise.
i built a stored procedure with inserting in to customers table. i have one column with identity. so want to take that identity column value in the same stored procedure. so how can i write that procedure with insert in to statements in that stored procedures.
can any one tell me. also how to get that value in ado.net 2.0. friends please tell me.
I've an existing SQL 2000 Stored Procedure that return data in many (~20) output parameters.
I'm starting to use it in a .Net c# application and it seems to insist that I setup all the output parameters: SqlParameter param = cmd.Parameters.Add("@BackgroundColour",SqlDbType.TinyInt); param.Direction=ParameterDirection.Output; even if I only need the value of a single one. Is this right? Is there a way to avoid coding every one every time?
EXEC('SELECT COUNT(docid) AS Total FROM docs WHERE ' + @QueryFilter)I want to get the cound as an output parameter.I can get output parameters to work only when I dont use EXEC. I need to use EXEC for this case since @QueryFilter gets generated in the stored procedure based on some some other data.How can I get that count using ouput parameter?
I've written a stored procedure that returns a value via an output parameter.
I'm calling the stored procedure in an sql session is a loop, and it passes the value back correctly the first time, but all subsequent calls the output parameter appears to have the same value. I believe that I'm making some very basic mistake, but I can't work it out.
Here's how I'm calling the stored procedure several times begin declare @instrumentid int exec GetInstrumentId 'OFX,AUDCHF,p,1,2007-03-20 16:54:21.843,2007-06-20,100.1', @instrumentid output; select @instrumentid exec GetInstrumentId 'OFX,AUDUSD,c,2,2007-03-20 16:54:21.843,2007-06-20,100.2', @instrumentid output; select @instrumentid exec GetInstrumentId 'OFX,AUDCHF,p,3,2007-03-20 16:54:21.843,2007-06-20,100.3', @instrumentid output; select @instrumentid end
And this is the start of the stored procedure
Create PROCEDURE [dbo].[GetInstrumentId] (@Ticket varchar(250), @InstrumentId int output) AS
If I call the stored procedure once it gives the corect output, if I call it several times the output parameter (@instrumentid ) never changes.
The following is a code snippit. My main interests are the OUT and OUTPUT parameter keywords. One returns a single value, and the other seemingly a resultset. OUTPUT returns a single value, however OUT seems to return a list of values. Could I please get this confirmed?
Also, I cannot see how the value being returned by OUT is being iterated...
Any help on the obove two matters is appreciated.
Thank You
Chris
BEGIN SNIPPET----------------------------------------------------------------------------------------------------------
--The following example creates the Production.usp_GetList
--stored procedure, which returns a list of products that have
--prices that do not exceed a specified amount.
USE AdventureWorks;
GO
IF OBJECT_ID ( 'Production.uspGetList', 'P' ) IS NOT NULL
I am stuck on how to syntactically retrieve an output value (@ProdCount) from a stored procedure. The SPROC works fine: the value of @ProdCount appears correctly in the output window. However, I can't retrieve it in the DAL handler (value remains 0). Does anyone have an idea on how to properly extract the return value. TIA for any pointers.SPROC (abridged): ALTER PROCEDURE and_Store_GetProductsByProdCatID_SortPage (@ProdCatID INT,...@ProdCount INT OUTPUT )
ASSELECT @ProdCount=(SELECT COUNT(*) FROM and_StoreProduct WHERE ProdCatID= @ProdCatID)DECLARE @SQL nvarchar(4000)SET @SQL = 'WITH tmpProd AS ( SELECT ROW_NUMBER() etc.. )SELECT ProdID, etc..FROM tmpProdWHERE Row BETWEEN etc..ORDER BY etc..'
EXECUTE(@SQL)RETURNDAL handler (abridged): Public Overloads Shared Function GetProductListByCatID(ByVal ProdCatID As Integer, ..., ByVal ProdCount As Integer) As List(Of Product) Dim productList As List(Of Product) = New List(Of Product) Try Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("conAnders").ConnectionString) Dim cmd As SqlCommand = New SqlCommand("and_Store_GetProductsByProdCatID_SortPage", con) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.AddWithValue("@ProdCatID", ProdCatID) '... cmd.Parameters.AddWithValue("@ProdCount", ProdCount) ' Output parm. Add dummy value.
Dim objProduct As Product 'Temp Product.
con.Open() Using myReader As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection) While myReader.Read() objProduct = New Product() With objProduct .ProdID = myReader.GetInt32(myReader.GetOrdinal("ProdID")) 'etc.. End With
productList.Add(objProduct) End While Dim tmp As Object = cmd.Parameters("@ProdCount").Value ' <-- Not updated
myReader.Close() End Using End Using Catch ex As Exception Throw ' Pass up the error. End Try Return productList End Function
I am trying to set up a stored procedure to return details about an item in my database. Say I use the following declarations for a stored procedure:
@Parameter1 int output, @Parameter2 varchar(200) output, @Parameter3 int output
and then I used a query like:
select @Parameter1 = table.field1, @Parameter2 = table.field2, @Parameter3 = table.field3 from table where itemID = 7
to populate the output parameters the problem I am running into is that if @Parameter1 is null, then @Parameter2 and @Parameter3 also return as null. But, If i rewrite the declarations to:
@Parameter3 int output, @Parameter2 varchar(200) output, @Parameter1 int output
then, with the same query, @Parameter3 and @Parameter2 get the values they should, even if @Parameter1 is null
does anyone have any ideas?
I guess another question is, I am right now in the code itself (not the demonstration here) returning 6 values, since this procedure will only ever return one record, I decided to implement it as output variables, rather than returning a 1 record result set to the application. Am I better off just returning the 1 record result set then parsing it out into variables in the application?
I'm trying to write an esqlc program that will run a stored procedure that returns several output parameters. I haven't been able to find any documentation to date that explains how to run the "EXEC SQL EXECUTE procname" command and specify the output parameters.
My stored procedure "aek_proc1" takes one input parameter (p1 - an 8-character string) and 3 output parameters (p2 - an integer; p3 - an 8-character string, and p4 a 40-character string).
My esqlc program contains the following code….
EXEC SQL BEGIN DECLARE SECTION; char p1[9]; int p2; char p3[9]; char p4[41]; WXEC SQL END DECLARE SECTION;
Any idea what I'm doing wrong or how it should be coded?
I'd really appreciate any advice you can offer!!
I've spend hours browsing this newsgroup and found lots of examples of how to do this in VB and from Query Analyser but I can't find any examples for ESQL/C that work.
I am a bit confused by an issue that I am having with executing an Oracle stored procedure (with an output parameter) using an ADO.NET connection object. I am able to get this working using an OLEDB connection, but I have no idea why the ADO.NET connection doesn't work. (Bug, by design, or my ignorance?) Actually, I can even get this to work if I use the .NET Providers for OLE DBMicrosoft OLE DB Provider for ORACLE if we set the connectionType to ADO.NET. This is the error that I am receiving:
[Execute SQL Task] Error: Executing the query "pkg_utility_read.test_out_var " failed with the following error: "The OracleParameterCollection only accepts non-null OracleParameter type objects, not SqlParameter objects.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.
It is also worth mentioning that the ORACLE stored procedure has an out parameter with a NUMBER datatype which I think maps to the ADO.NET Int32 datatype. I guess OLE DB datatypes are more closely mapped to ORACLE datatypes. In OLE DB you can set the parameter to double and the ORACLE stored procedure to NUMBER and it works.
I have coded a stored procedure to return nearly all of the columns of a single record selected by using a unique key value. The record is in an SQL database, not within an in-memory DataSet. All of the parameters that I wish to have returned to my program are defined as OUTPUT; the two key values are defaulted to INPUT, as there is no need to return them to the calling program. I also have defined the direction of these parameters in the calling SQLDataAdapter function. However, when I run this, the values returned are either the current date for my DateTime parameters, Nothing for my Char parameters or 0's for my integer parameters.
When I try testing the sproc alone, by using the "Step Into Stored Procedure" action in Visual Studio, I get a message in the Debug Output window indicating that parameter @TktClassID was expected and not supplied. This is an OUTPUT parameter, which makes me question why I should be providing any sort of value for it within my VB code. Following are the function definition from my SQLDataAdapter class that calls my sproc, and the sproc itself. I appreciate any help that anyone can provide.
**FUNCTION DEFINITION FROM SQLDataAdapter Class
Public Function Fetch(ByVal ticket As Ticket) As Ticket Dim connbuilder As New System.Data.SqlClient.SqlConnectionStringBuilder connbuilder("Data Source") = "ITS-KCGV7VZSQLEXPRESS" connbuilder("Integrated Security") = "True" connbuilder("Initial Catalog") = "ITSHelpDesk" Using conn As New System.Data.SqlClient.SqlConnection(connbuilder.ConnectionString)
Using comm As New System.Data.SqlClient.SqlCommand("dbo.TicketFetch", conn) conn.Open() comm.CommandType = CommandType.StoredProcedure Dim parm As System.Data.SqlClient.SqlParameter
In a Database "AP" of my SQL Server Management Studio Express (SSMSE), I have a stored procedure "spInvTotal3":
CREATE PROC [dbo].[spInvTotal3]
@InvTotal money OUTPUT,
@DateVar smalldatetime = NULL,
@VendorVar varchar(40) = '%'
This stored procedure "spInvTotal3" worked nicely and I got the Results: My Invoice Total = $2,211.01 in my SSMSE by using either of 2 sets of the following EXEC code: (1) USE AP GO --Code that passes the parameters by position DECLARE @MyInvTotal money EXEC spInvTotal3 @MyInvTotal OUTPUT, '2006-06-01', 'P%' PRINT 'My Invoice Total = $' + CONVERT(varchar,@MyInvTotal,1) GO (2) USE AP GO DECLARE @InvTotal as money EXEC spInvTotal3 @InvTotal = @InvTotal OUTPUT, @DateVar = '2006-06-01', @VendorVar = '%' SELECT @InvTotal GO //////////////////////////////////////////////////////////////////////////////////////////// Now, I want to print out the result of @InvTotal OUTPUT in the Windows Application of my ADO.NET 2.0-VB 2005 Express programming. I have created a project "spInvTotal.vb" in my VB 2005 Express with the following code:
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.SqlTypes
Public Class Form1
Public Sub printMyInvTotal()
Dim connectionString As String = "Data Source=.SQLEXPRESS; Initial Catalog=AP; Integrated Security=SSPI;"
Dim conn As SqlConnection = New SqlConnection(connectionString)
Try
conn.Open()
Dim cmd As New SqlCommand
cmd.Connection = conn
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "[dbo].[spInvTotal3]"
Dim param As New SqlParameter("@InvTotal", SqlDbType.Money)
param.Direction = ParameterDirection.Output
cmd.Parameters.Add(param)
cmd.ExecuteNonQuery()
'Print out the InvTotal in TextBox1
TextBox1.Text = param.Value
Catch ex As Exception
MessageBox.Show(ex.Message)
Throw
Finally
conn.Close()
End Try
End Sub
End Class ///////////////////////////////////////////////////////////////////// I executed the above code and I got no errors, no warnings and no output in the TextBox1 for the result of "InvTotal"!!?? I have 4 questions to ask for solving the problems in this project: #1 Question: I do not know how to do the "DataBinding" for "Name" in the "Text.Box1". How can I do it? #2 Question: Did I set the CommandType property of the command object to CommandType.StoredProcedure correctly? #3 Question: How can I define the 1 output parameter (@InvTotal) and 2 input parameters (@DateVar and @VendorVar), add them to the Parameters Collection of the command object, and set their values before I execute the command? #4 Question: If I miss anything in print out the result for this project, what do I miss?
Inside some TSQL programmable object (a SP/or a query in Management Studio)I have a parameter containing the name of a StoreProcedure+The required Argument for these SP. (for example it's between the brackets [])
I can't change thoses SP, (and i don't have a nice output param to cach, as i would need to change the SP Definition)All these SP 'return' a 'select' of 1 record the same datatype ie: NVARCHAR. Unfortunately there is no output param (it would have been so easy otherwise. So I am working on something like this but I 'can't find anything working
Hi, I wants to bind textbox with sqldatasource in c#.net so I am using following code and has following error... Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.Source Error:
Line 22: Line 23: System.Data.DataView dv = (DataView) SqlDataSource1.Select(System.Web.UI.DataSourceSelectArguments.Empty);Line 24: TextBox1.Text = dv[0]["Proid"].ToString();Line 25: Line 26: }Please, anybody knows solution tell me
I have a SQL database with 1 column in it.. it is a do not call registry for my office. I want to make a web application so our leads can go on the web and request to be put on the do not call list. problem is, if their number already exists, it gets a violation of primary key... Normal handling for this would be to do a select query based on user input, and if it exists in the database, tell them that, else do the insert query... Problem is, i cant seem to figure out how to bind the result of the select query to a textbox or label so i can compare the results to do that logic. Any ideas? This is in asp .net 2.0. Thanks! -Dan
I'm trying to develop a VB.NET (2005) form with just a ComBobox and a TextBox.
I bind a combobox with the SqlCeResultset (Scrollable | Updatable ). Do the same with the TextBox. Combobox1.DataSource = rsResultSet TextBox1.DataBindings.Add("Text", rsResultSet, "Obs")
This works (when I change the Combo item the textbox changes as well) but any changes to the textbox text do not reach the DB.If i change the Combobox item and back the old data is still there. If i look at the result set it does appear as updateable.
How can I update the SqlCeResultset when I change the TextBox text?
I have a strange problem with an OleDB call to a stored procedure thatreturns a rowset.Only the first time I execute the query, after I restart SqlServer, myprogram crashes becausethe rowset is empty. All next calls (after restarting my program, ofcourse) run successfully.The context is:1) if I do not bind the output rowset, my program doesn't crash2) If I run the call without the binding and then I run the call withthe binding, it doesn't crash3) It is not the first query I do in my session4) the call crashes only if in the SP there are some inserts: it is awell known problem with OleDB, but in manyother cases I have fixed it setting NOCOUNT to ON
I have some problem about bind field from stored procedure to report.
Now I have dataset that come form stored procedure. In Dataset Dialog, "Fields" tab, I add Fieldname like fieldname in stored procedure. And "Parameters" tab, I add parameters those are neccessary for my stored procedure.
I test on data tab view. When I click "!" to run, then there is input dialog parameter. I filled it, then the result is ok.
But when I build project, I noticed warning message....
[rsMissingFieldInDataSet] The data set €˜MyDataSet€™ contains a definition for the Field €˜MyField€™. This field is missing from the returned result set from the data source. c:.....visual studio 2005projects eport project1 eport project1Report7.rdl 0 0
[rsErrorReadingDataSetField] The data set €˜MyDataSet€™ contains a definition for the Field €˜MyField€™. The data extension returned an error during reading the field. There is no data for the field at position 6. c:.....visual studio 2005projects eport project1 eport project1Report7.rdl 0 0
After I build my project, I run the report, each textbox that binded field, display empty value.
What happen with my report? And how can I solve this problem?
ALTER PROCEDURE [dbo].[ReportChart]@Num int,@patID char(16) ASbegin if @Num=2 Begin select * from table1 where patientid=@patID End else If @Num=1 Begin select * from table2 where patientid=@patID End end
While using the above stored procedure, when i bind it with Dataset. The fields corresponding to table1 are displayed in the Fields Tab of the Dataset whereas the Fields corresponding to table2 are not displayed. Please help me out . Thanks In Advance Regards Navdeep
Hi there everyone. I have a stored procedure called “PagingTable� that I use for performing searches and specifying how many results to show per ‘page’ and which page I want to see. This allows me to do my paging on the server-side (the database tier) and only the results that actually get shown on the webpage fly across from my database server to my web server. The code might look something like this:
The problem is the stored procedure actually returns two result sets. The first result set contains information regarding the total number of results founds, the number of pages and the current page. The second result set contains the data to be shown (the columns specified). In ‘classic’ ASP I did this like this.
'Open the recordset rsItems.Open strSQL, conn, 0, 1
'Get the values required for drawing the paging table intCurrentPage = rsItems.Fields("CurrentPage").Value intTotalPages = rsItems.Fields("TotalPages").Value intTotalRows = rsItems.Fields("TotalRows").Value
'Advance to the next recordset Set rsItems = rsItems.NextRecordset
I am trying to do this now in ASP.NET 2.0 using the datasource control and the repeater control. Any idea how I can accomplish two things:
A) Bind the repeater control to the second resultset B) Build a “pager� of some sort using the values from the first resultset
My task is to add income by taking few variables from webpage. I had take User ID(From database), Field value by selecting it from DropDownBox( Which value is once again taken from database), Income Description, Date, Amount . I had completed this task successfully by binding DropDownBox to database by query string and added income using stored procedure as below.
I need this to be done using only single Stored Procedure for binding Field Value to DropDownBox and for adding income. Plz tell me how to do this? ASPX.CS file protected void Page_Load(object sender, EventArgs e) { SqlConnection con = null;
con = DataBaseConnection.GetConnection(); DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter("select PA_IFName from PA_IncomeFields where PA_UID=@PA_UID", con); da.SelectCommand.Parameters.Add("@PA_UID", SqlDbType.Int).Value = (int)Session["PA_UID"]; da.Fill(ds);
I have a Lookup Transformation that matches the natural key of a dimension member and returns the dimension key for that member (surrogate key pipeline stuff).
I am using an OLE DB Command as the Error flow of the Lookup Transformation to insert an "Inferred Member" (new row) into a dimension table if the Lookup fails.
The OLE DB Command calls a stored procedure (dbo.InsertNewDimensionMember) that inserts the new member and returns the key of the new member (using scope_identity) as an output.
What is the syntax in the SQL Command line of the OLE DB Command Transformation to set the output of the stored procedure as an Output Column?
I know that I can 1) add a second Lookup with "Enable memory restriction" on (no caching) in the Success data flow after the OLE DB Command, 2) find the newly inserted member, and 3) Union both Lookup results together, but this is a large dimension table (several million rows) and searching for the newly inserted dimension member seems excessive, especially since I have the ID I want returned as output from the stored procedure that inserted it.
Thanks in advance for any assistance you can provide.
ex: myprocedure(@Cusname varchar(50), @Cusid int output)as Insert into Customer(Cusname) values (@Cusname)SELECT @cusid = @@IDENTITY i add the query to my adapter called CreatCustomer (@Cusnam,@Cusid)private Merp_CusListTableAdapter _CuslistAdapter = null;protected Merp_CusListTableAdapter Adapter { get {if (_CuslistAdapter == null) _CuslistAdapter = new Merp_CusListTableAdapter();return _CuslistAdapter; } } Now how i write function in BLL to receive output paramter from creatcustomer function?
Hi,I have a stored procedure which expects a Null value if a user does not enter something into a TextBox. The query should return all rows if this case.The stored procedure works as expected in Query Analyzer, but my application does not seem to send a Null and no rows are returned. Any ideas?Thanks.ps I am using SqlDataSource and GridView, this is the first time I have tried to connect to a database with asp.net.
I have written a simple C# console application that create my own Stored Procedures the code is here ----------------------------------------------------------------------------
static void Main(string[] args) { SqlConnection cn; string strSql; string strConnection; SqlCommand cmd; strConnection="server=(local);database=Northwind;integrated security=true;"; strSql="CREATE PROCEDURE spmahdi @CustomerID nchar(5) @counter int OUTPUT AS SELECT OrderID, OrderDate,RequiredDate,ShippedDate FROM Orders WHERE CustomerID = @CustomerID ORDER BY OrderID SET @counter=@@rowcount"; cn=new SqlConnection(strConnection); cn.Open(); cmd=new SqlCommand(strSql,cn); cmd.ExecuteNonQuery(); cn.Close(); Console.WriteLine("Procedure Created!"); }
------------------------------------------------------------------------------------ but it has some errors becuase of my strSql strSql="CREATE PROCEDURE spmahdi @CustomerID nchar(5) @counter int OUTPUT AS SELECT OrderID, OrderDate,RequiredDate,ShippedDate FROM Orders WHERE CustomerID = @CustomerID ORDER BY OrderID SET @counter=@@rowcount"; I mean in creating the stored procedure if i delete the Output parameter from my stored procedure and my strSql would be somethimg like this strSql="CREATE PROCEDURE spmahdi @CustomerID nchar(5) AS SELECT OrderID, OrderDate,RequiredDate,ShippedDate FROM Orders WHERE CustomerID = @CustomerID ORDER BY OrderID "; There will be no errors I use Visual Studio.NET 2003(full versoin)and MSDE(not Sql Server) Could someone help me solve this problem? Thanks and Regards.
I've read that stored procedures should use output parameters instead ofrecordsets where possible for best efficiency. Unfortunately I need toquantify this with some hard data and I'm not sure which counters touse. Should I be looking at the SQL Server memory counters or somethingelse.*** Sent via Developersdex http://www.developersdex.com ***Don't just participate in USENET...get rewarded for it!
I admit I am a novice to queries and stored procedures but understand stored procedures are more secure, so I am choosing to challenge myself with a stored procedure and have not been successful at all.
What I am looking for is a stored procedure which would query the single table named Hospital, which would search from a single textbox the end user would enter the text they are searching for on a Windows VB application but is dependant on a few end user selected items.
1. The end user can select a radio button either "Starts with" or "Contains" 2. The end user can select from 6 checkboxes (Hospitals, Address, City, State, Zip, Type) to limit or expand their search from the columns in the table.
The table has 17columns (CO, PARENTCO, ADDR, POBox, CITY, State, ZIP, TEL, FAX, WEBSITE, HOSP_TYPE, OWNERSHIP, BEDS, CONTACT, TITLE, Email) but I am only allowing the end user to search by the above 6 columns and need to display the above 6 columns plus the phone, fax and website columns.
After the user clicks the search button it displays the results in a listbox and the user will then select the one they want and it displays the information in another set of textboxes.
Hopefully someone can get me pointed in the right direction! Thanks for your help!
I'm trying to take the output of the Render method and bind it to the ReportViewer control. First of all, is this possible? If so, what is the best way to render the report (format: XML,CSV, NULL, etc), and then how to I 'bind' the result to the control?
I'm proving some code to demonstrate how I'm rendering the report: ... string format = "XML"; string devInfo = @"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>"; ReportExecutionService rs = new ReportExecutionService(); ExecutionInfo execInfo = new ExecutionInfo(); ExecutionHeader execHeader = new ExecutionHeader(); byte[] result= null;
rs.ExecutionHeaderValue = execHeader; execInfo = rs.LoadReport(path, null); string SessionId = rs.ExecutionHeaderValue.ExecutionID; result = rs.Render(format, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);
Thanks, any help would be greatly appreciated. Peter