How To Code ASP.NET Page With Return Value Store Procedure?
Apr 12, 2005
Does anyone know how to call a SQL store procedure that return a value to the page?
I've a simple data entry aspx page with several textboxes and a save button. When user fill out the form and click save/submit, it calls a store procedure to insert a row into a SQL table and automatically generate an ID that need to return the the page to display for the user.
My stored procedure works and codes is working except I need to capture the return value from the stored procedure and use that value in my code behind page to indicate that a duplicate record entry was attempted. In my code behind file (VB) how would I capture the value "@myERROR" then display in the label I have that a duplicate entry was attempted. Stored ProcedureCREATE PROCEDURE dbo.usp_InsertNew @IDNumber nvarchar(25), @ID nvarchar(50), @LName varchar(50), @FName varchar(50) AS DECLARE @myERROR int -- local @@ERROR , @myRowCount int --local @@rowcountBEGIN -- See if a contact with the same name and zip code exists IF EXISTS (Select * FROM Info WHERE ID = @ID) BEGIN RETURN 1END ELSEBEGIN TRAN INSERT INTO Info(IDNumber, ID, LName, FName) VALUES (@IDNumber, @ID, @LName, @FName) SELECT @myERROR = @@ERROR, @myRowCount = @@ROWCOUNT If @myERROR !=0 GOTO HANDLE_ERROR COMMIT TRAN RETURN 0 HANDLE_ERROR: ROLLBACK TRAN RETURN @myERROR ENDGO asp.net page<asp:SqlDataSource ID="ContactDetailDS" runat="server" ConnectionString="<%$ ConnectionStrings:EssPerLisCS %>" SelectCommand="SELECT * FROM TABLE_One" UpdateCommand="UPDATE TABLE_One WHERE ID = @ID" InsertCommand="usp_InsertNew" InsertCommandType="StoredProcedure"> <SelectParameters> <asp:ControlParameter ControlID="GridView1" Name="ID" PropertyName="SelectedValue" /> </SelectParameters> </asp:SqlDataSource>
how do i return the identity from stored procedure to asp.net code behind page? CREATE PROCEDURE [dbo].[myInsert] ( @Name varchar(35), @LastIdentityNumber int output)AS insert into table1 (name) values (@name) DECLARE @IdentityNumber intSET @IdentityNumber = SCOPE_IDENTITY()SELECT @IdentityNumber as LastIdentityNumber code behind: public void _Insert( string _Name, { DbCommand dbCommand = db.GetStoredProcCommand("name_Insert");db.AddInParameter(dbCommand, "name", DbType.String, _userId); db.AddParameter(dbCommand, "@IdentityNumber", DbType.Int32, ParameterDirection.Output, "", DataRowVersion.Current, null); db.ExecuteNonQuery(dbCommand); int a = (int)db.GetParameterValue(dbCommand,"@IdentityNumber"); whats wrong with to the above code?
I have a package that I have been attempting to return a error code after the stored procedure executes, otherwise the package works great.
I call the stored procedure from a Execute SQL Task (execute Marketing_extract_history_load_test ?, ? OUTPUT) The sql task rowset is set to NONE. It is a OLEB connection.
I have two parameters mapped:
tablename input varchar 0 (this variable is set earlier in a foreach loop) ADO. returnvalue output long 1
I set the breakpoint and see the values change, but I have a OnFailure conditon set if it returns a failure. The failure is ignored and the package completes. No quite what I wanted.
The first part of the sp is below and I set the value @i and return.
Why is it not capturing and setting the error and execute my OnFailure code? I have tried setting one of my parameter mappings to returnvalue with no success.
I spent about an hour searching the forums and the web but could not find a solution. Bob Bojanic, if you are around can you answer?
I have a DB that stores WW data for company names in a varchar
I don't have control over this DB, other than to pull data from it
I have an SSIS package that grabs WW data in a single pull using a system account
I have an Execute SQL task that runs a sproc to stage the data
I have a Data Flow Task that then copies the data to another server (where I need it)
The destination columns are nvarchar. The source columns are varchar. Some countries (such as Korea and China) end up with ASCII gibberish (because of code page issues).
I have a solution that involves pulling the data, BCP the pulled data to a text file, then re-import with the correct code page, and delete the gibberish. BUT, I'd like to do this as part of the pull if possible (without any data duplication).
I've tried modifying the CodePage properties for both the Staging step (Execute SQL task running a sproc) and the Source & Dest columns for the Data Flow Task with no luck. Can anyone assist? Thanks much!
Dear All, I read through all the post and flipped through the books but Istill can't find the answer to my problem.I'm inserting a new record via a stored procedure and want to return the idvia scope_identity, which I thought would be preety straight forward.The code I'm using is below and this keeps giving me "Multiple-step OLE DBoperation generated errors. Check each OLE DB status value, if available. Nowork was done."How do I pick the returning id value and could anyone see were I'm goingwrong below.Many thanks for any help you can offer.CREATE PROCEDURE [sp_insert_address]@ADDR_NAME_2 [char](70),@ADDR_NO_3 [char](10),@ADDR_ROAD_4 [char](50),@ADDR_DISTRICT_5 [char](50),@ADDR_TOWN_6 [char](50),@ADDR_BOROUGH_7 [char](50),@ADDR_PCODE_8 [char](12),@addr_id [int] OUTPUTAS INSERT INTO [HEAPADLive].[dbo].[TBL_ADDR]([ADDR_NAME],[ADDR_NO],[ADDR_ROAD],[ADDR_DISTRICT],[ADDR_TOWN],[ADDR_BOROUGH],[ADDR_PCODE])VALUES(@ADDR_NAME_2,@ADDR_NO_3,@ADDR_ROAD_4,@ADDR_DISTRICT_5,@ADDR_TOWN_6,@ADDR_BOROUGH_7,@ADDR_PCODE_8)set @addr_id = scope_identity()GO
I have a store procedure called ValidateUser which retrtive an authneticated ID from a database. This procedure is defined as follow :
Code Snippet ALTER PROCEDURE [dbo].[ValidateUser] -- Add the parameters for the stored procedure here @LoginId int = 0 OUTPUT, @UserName varchar(50), @pw varchar(60), @LineId varchar(16) AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON;
-- return the User id as validted SELECT @loginID = Id FROM [NomosConfig].[dbo].Users WHERE [UserName] = @UserName AND [PassWord] = @pw AND [LineId] = @LineId -- if no record returns, the request user is not allowed if @@ROWCOUNT < 1 SELECT @loginID = 0
END
Runing this procesdure alone work well and return correct LoginId
What I would like to do is retrieve that return LoginID inside an other procedure. For that I am doinmg as follow :
Code Snippet DECLARE @AuthenticatedUserId int;
-- verify that user is authorized to access to PSU login EXECUTE @AuthenticatedUserId= [ValidateUser] @UserName ='cal' ,@pw ='cal' ,@LineId='PR495250' SELECT @AuthenticatedUserId
What is strange is that the @AuthenticatedUserId is always retunring 0 .. Did I write something wrong ?
Hi All, I have to return a string value from the store procedure. If condition success BEGIN RETURN 'Success' END ELSE BEGIN RETURN 'Fail' ENDI am retrieving this value with ExecuteReturnQuery() method. But it gives me the error like "Conversion failed when converting the varchar value to data type int."can anyone please help me for this?Thank you.Regards.
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 All, I have written a stored procedure that has a return value (OUTPUT Parameter) and was wondering if there is any way to retreive this value in SQL Server Reporting Services 2005? I get the result fine, but cannot figure out how to get the return parameter.
Dear friends,I have a problem with a simple select statement and I don't know why it is happening.I have 2 tables, Fees and FeesDataRoles. Fees presents all the fees and FeesDataRole is a middle table between Fees and Roles table. So each fee can have multiple Roles and a Role can have many Fees.Now I have a select statement:Select *From Fees Inner Join FeesDataRoles ON Fees.FeeID = FeesDataRoles.FeeIDWhere (FeesDataRoles.DataRoleID = @DataRoleID) AND (FeesDataRoles.RecordStatus = 1 ) AND (FeesDataRoles.ValidFrom >= getdate() ) AND ( FeesDataRoles.ValidTo <= getdate() OR FeesDataRoles.ValidTo is null)Now it shouldn't take that long to execute this procedure but surprisingly sometimes when I insert a value to the table and then execute this store procedure it does now show the data just added. Very strange.....!!!!I ran the procedure 5 times after inserting an item and nearly 1 out of 5 does not return the right result righ. ( It does not include the recently inserted rows)Anyone have any idea....?I used Tuning Advisor, no sugestion. I change the clustered index in FeesDataRoles from FeesDataRoleID(the primary key of the table) to DataRoleID to increase the performance, still it happens sometimes.Is my Where clause so costly that cause this problem.Please help. I really appreciate your help.Regards,Mehdi
My store procedure get the QuestionID (PK) from the page and then it's to return a few varchars but gives me the error that string can't be converted to int. ALTER PROCEDURE [dbo].[usp_getQuestionsforEditPopulateText]@QuestionID int,@QuestionDescription varchar(MAX) OUTPUT,@Option1 varchar(50) OUTPUT,@Option2 varchar(50) OUTPUT,@Option3 varchar(50) OUTPUT,@Option4 varchar(50) OUTPUT,@Option5 varchar(50) OUTPUT,@reference varchar(50) OUTPUT,@chb1 int OUTPUT,@chb2 int OUTPUT,@chb3 int OUTPUT,@chb4 int OUTPUT,@chb5 int OUTPUTAsSet @QuestionDescription =(Select questionDescription from QuestionsBank Where questionID = @QuestionID)Set @Option1 =(Select optionDescription from options Where questionID = @QuestionID and optionNumber = 1)Set @Option2 =(Select optionDescription from options Where questionID = @QuestionID and optionNumber = 2)Set @Option3 =(Select optionDescription from options Where questionID = @QuestionID and optionNumber = 3)Set @Option4 =(Select optionDescription from options Where questionID = @QuestionID and optionNumber = 4)Set @Option5 =(Select optionDescription from options Where questionID = @QuestionID and optionNumber = 5)Set @reference = (Select referencedescription from reference where questionID = @QuestionID)Set @chb1 = (Select correctOption from options where questionID = @QuestionID and optionNumber = 1)Set @chb2 = (Select correctOption from options where questionID = @QuestionID and optionNumber = 2)Set @chb3 = (Select correctOption from options where questionID = @QuestionID and optionNumber = 3)Set @chb4 = (Select correctOption from options where questionID = @QuestionID and optionNumber = 4)Set @chb5 = (Select correctOption from options where questionID = @QuestionID and optionNumber = 5) RETURN This is what the page callsDim dbConnection As System.Data.IDbConnection = New System.Data.SqlClient.SqlConnection("myconnectionstring ") Dim cmdUpdate As New Data.SqlClient.SqlCommand("usp_getQuestionsforEditPopulateText", dbConnection) cmdUpdate.CommandType = Data.CommandType.StoredProcedure cmdUpdate.Parameters.Add(New Data.SqlClient.SqlParameter("@QuestionID", Data.SqlDbType.Int)) cmdUpdate.Parameters("@QuestionID").Value = QuestionID cmdUpdate.Parameters.Add(New Data.SqlClient.SqlParameter("@QuestionDescription", Data.SqlDbType.VarChar)) cmdUpdate.Parameters("@QuestionDescription").Direction = Data.ParameterDirection.Output cmdUpdate.Parameters.Add(New Data.SqlClient.SqlParameter("@Option1", Data.SqlDbType.VarChar)) cmdUpdate.Parameters("@Option1").Direction = Data.ParameterDirection.Output cmdUpdate.Parameters.Add(New Data.SqlClient.SqlParameter("@Option2", Data.SqlDbType.VarChar)) cmdUpdate.Parameters("@Option2").Direction = Data.ParameterDirection.Output cmdUpdate.Parameters.Add(New Data.SqlClient.SqlParameter("@Option3", Data.SqlDbType.VarChar)) cmdUpdate.Parameters("@Option3").Direction = Data.ParameterDirection.Output cmdUpdate.Parameters.Add(New Data.SqlClient.SqlParameter("@Option4", Data.SqlDbType.VarChar)) cmdUpdate.Parameters("@Option4").Direction = Data.ParameterDirection.Output cmdUpdate.Parameters.Add(New Data.SqlClient.SqlParameter("@Option5", Data.SqlDbType.VarChar)) cmdUpdate.Parameters("@Option5").Direction = Data.ParameterDirection.Output cmdUpdate.Parameters.Add(New Data.SqlClient.SqlParameter("@reference", Data.SqlDbType.VarChar)) cmdUpdate.Parameters("@reference").Direction = Data.ParameterDirection.Output cmdUpdate.Parameters.Add(New Data.SqlClient.SqlParameter("@chb1", Data.SqlDbType.Int)) cmdUpdate.Parameters("@chb1").Direction = Data.ParameterDirection.Output cmdUpdate.Parameters.Add(New Data.SqlClient.SqlParameter("@chb2", Data.SqlDbType.Int)) cmdUpdate.Parameters("@chb2").Direction = Data.ParameterDirection.Output cmdUpdate.Parameters.Add(New Data.SqlClient.SqlParameter("@chb3", Data.SqlDbType.Int)) cmdUpdate.Parameters("@chb3").Direction = Data.ParameterDirection.Output cmdUpdate.Parameters.Add(New Data.SqlClient.SqlParameter("@chb4", Data.SqlDbType.Int)) cmdUpdate.Parameters("@chb4").Direction = Data.ParameterDirection.Output cmdUpdate.Parameters.Add(New Data.SqlClient.SqlParameter("@chb5", Data.SqlDbType.Int)) cmdUpdate.Parameters("@chb5").Direction = Data.ParameterDirection.Output 'open connection dbConnection.Open() 'Execute non query cmdUpdate.ExecuteNonQuery() 'close connection dbConnection.Close()
I use new query to execute my store procedure but didnt return any value is that any error for my sql statement??
USE [Pharmacy_posicnet] GO /****** Object: StoredProcedure [dbo].[usp_sysconf] Script Date: 22/07/2015 4:01:38 PM ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER procedure [dbo].[usp_sysconf]
Hi all,Anyone can show me how can I catch the 'Print' statement that I have defined in my store procedure using SQL server 2000 DB on the .aspx page? ( I am using ASP.NET 1.0)My store procedure as follow:CREATE PROC NewAcctType(@acctType VARCHAR(20))ASBEGIN --checks if the new account type is already exist IF EXISTS (SELECT * FROM AcctTypeCatalog WHERE acctType = @acctType) BEGIN PRINT 'The account type is already exist' RETURN END BEGIN TRANSACTION INSERT INTO AcctTypeCatalog (acctType) VALUES (@acctType) --if there is an error on the insertion, rolls back the transaction; otherwise, commits the transaction IF @@error <> 0 OR @@rowcount <> 1 BEGIN ROLLBACK TRANSACTION PRINT 'Insertion failure on AcctTypeCatalog table.' RETURN END ELSE BEGIN COMMIT TRANSACTION ENDENDThanks for all your replies
Is anyone has store procedure that find city and zipcode by radius (10 miles, 30 miles, 50 miles.......) and also table that has all zipcodes. I finded one, but it's look like very old one, not updated since 2005
Hi I was transferring objects of my existing database from remote to local and I recieved this error during the DTS process. It was on the transfer of the following stored procedure. I tried to create this SP manually but its giving me the same error and doesn't create it. I don't know how to fix it. I wonder if somebody can help me! Thanks in Advance [450] Code page translations are not supported for the text data type. From: 1252 To: 1256. CREATE PROCEDURE dbo.Novasoft_DL_UpdateDownloadsRating @RatingID int, @DownloadID int, @UserID int, @Rating int, @Comment text, @ReviewDate datetime, @CommentName nvarchar(50) ASUPDATE dbo.Novasoft_DL_DownloadsRating SET [DownloadID] = @DownloadID, [UserID] = @UserID, [Rating] = @Rating, [Comment] = @Comment, [ReviewDate] = @ReviewDate, [CommentName] = @CommentNameWHERE [RatingID] = @RatingID GO
My stored proceddure "My Programs" includes a parameter @meid.How do I code an aspx file to run the procedure with a user ID, e.g. EmpID?I tried the following codes, but the error message indicated it can not findthe Stored Procedure. How do I pass the EmpID as a Stored Procedure parameter? <%meid = EmpIdcmd.CommandText = "MyPrograms meid"cmd.CommandType = CommandType.StoredProcedurecmd.Connection = sqlConnection2sqlConnection2.Open()reader3 = cmd.ExecuteReader(meid)While reader3.Read()sb.Append(reader3(i).ToString() + "......<BR> <BR /> ")End While%> TIA,Jeffrey
Hi ! I have a problem with the unique identifier and don't know how to solve it. I have a stored procedure, called from my ASP.NET page, which inserts a new record into a table. I need to get the Id of the row just inserted in order to use it as a parameter of another stored procedure which inserts a new row with this value and other values. I tried with SCOPE_IDENTITY but i don't know how to ask for this value to the first stored procedure and stored it into an ASP variable. Dim cmd As New SqlCommand cmd.CommandText = "Insertar_Contacto" cmd.CommandType = CommandType.StoredProcedure cmd.Connection = connect Thanks!!
We are executing a SSIS package using a xp_cmdshell command in a SP as shown below. This package does consumes time to execute almost 90 minutes and does get executed successfully too. But the strange thing is we don't get the result in @result variable just because somehow the next sql statement after the below highlighted statement doesn't get executed at all. After checking execution stats for the SP using the query attached below we observed that somehow the SP vanishes out of the execution stats for the server.
I'm trying to figure this out I have a store procedure that return the userId if a user exists in my table, return 0 otherwise ------------------------------------------------------------------------ Create Procedure spUpdatePasswordByUserId @userName varchar(20), @password varchar(20) AS Begin Declare @userId int Select @userId = (Select userId from userInfo Where userName = @userName and password = @password) if (@userId > 0) return @userId else return 0 ------------------------------------------------------------------ I create a function called UpdatePasswordByUserId in my dataset with the above stored procedure that returns a scalar value. When I preview the data from the table adapter in my dataset, it spits out the right value. But when I call this UpdatepasswordByUserId from an asp.net page, it returns null/blank/0 passport.UserInfoTableAdapters oUserInfo = new UserInfoTableAdapters(); Response.Write("userId: " + oUserInfo.UpdatePasswordByUserId(txtUserName.text, txtPassword.text) ); Do you guys have any idea why?
This is my function, it returns SQLDataReader to DATALIST control. How to return page number with the SQLDataReader set ? sql server 2005, asp.net 2.0
Function get_all_events() As SqlDataReader Dim myConnection As New SqlConnection(ConfigurationManager.AppSettings("...........")) Dim myCommand As New SqlCommand("EVENTS_LIST_BY_REGION_ALL", myConnection) myCommand.CommandType = CommandType.StoredProcedure
Dim parameterState As New SqlParameter("@State", SqlDbType.VarChar, 2) parameterState.Value = Request.Params("State") myCommand.Parameters.Add(parameterState)
Dim parameterPagesize As New SqlParameter("@pagesize", SqlDbType.Int, 4) parameterPagesize.Value = 20 myCommand.Parameters.Add(parameterPagesize)
Dim parameterPagenum As New SqlParameter("@pageNum", SqlDbType.Int, 4) parameterPagenum.Value = pn1.SelectedPage myCommand.Parameters.Add(parameterPagenum)
Dim parameterPageCount As New SqlParameter("@pagecount", SqlDbType.Int, 4) parameterPageCount.Direction = ParameterDirection.ReturnValue myCommand.Parameters.Add(parameterPageCount)
myConnection.Open() 'myCommand.ExecuteReader(CommandBehavior.CloseConnection) 'pages = CType(myCommand.Parameters("@pagecount").Value, Integer) Return myCommand.ExecuteReader(CommandBehavior.CloseConnection) End Function
Variable Pages is global integer.
This is what i am calling DataList1.DataSource = get_all_events() DataList1.DataBind()
How to return records and also the return value of pagecount ? i tried many options, nothing work. Please help !!. I am struck
Just getting started with SQL Server CLR integration. Any suggestions on how to organize code? Should I keep my CLR Stored Procedures in a separate project than the code that will call them? Should each DB have its own project containing all the CLR code?
Maybe there is no right way...I'm just looking for a good way.
I am almost done with a simple page to have a user select a file (using the FileUpload object), give it a short description and associate it with an item from a listbox. Thensave these pieces of data to a new row in a SQL DB. My issue... The SQLSmd.ExecuteNonQuery FAILS... I have got all the fields able to connect and almost save... but for the actual "document" field errors out. The user can select any type of file (image, word, excel, Powerpoint, etc) for storage into the DB. I am not storing a referance to a file or the path to a file but the actual file in SQL.In the DB I have the field (Document) set to a type of VarBinary(8000) in the table. Here is thethe corrisponding code in my app... Dim bArray As Byte...bArray = FileUpload1.PostedFile.InputStream.ReadByte()... SQLCmd.Parameters.Add("@Document", Data.SqlDbType.VarBinary, 8000).Value = bArray...iReturn = SQLCmd.ExecuteNonQuery() ERRORThe first section of the stact trace... [InvalidCastException: Invalid cast from 'System.Byte' to 'System.Byte[]'.] System.Convert.DefaultToType(IConvertible value, Type targetType, IFormatProvider provider) +867 System.Byte.System.IConvertible.ToType(Type type, IFormatProvider provider) +37 System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider) +408 System.Data.SqlClient.SqlParameter.CoerceValue(Object value, MetaType destinationType) +896
I excute sp_columns in my Stored Procedure script to get the data type of a table column. EXEC sp_columns @table_name = 'XXX', @column_name='YYY' How do i store the column 'TYPE_NAME' in the return row into a variable so that i can use it later in my stored procedure? Thanks Hannah