Search Results

Search found 191 results on 8 pages for 'storedprocedure'.

Page 6/8 | < Previous Page | 2 3 4 5 6 7 8  | Next Page >

  • Please take a stab at this VB.Net Oracle-related sample and help me with String.Format.

    - by Hamish Grubijan
    If the database is not Oracle, it is MS SQl 2008. My task: if Oracle, add two more parameters when calling a stored proc. Oracle and MSFT stored procs are generated; Oracle ones have 3 extra parameters: Vret_val out number, Vparam2 in out number, Vparam3 in out number, ... the rest (The are not actually named Vparam2 and Vparam3, but this should not matter). So, the code for a helper VB.Net class that calls a stored proc: Imports System.Data.Odbc Imports System.Configuration Dim objCon As OdbcConnection = Nothing Dim objAdapter As OdbcDataAdapter Dim cmdCommand As New OdbcCommand Dim objDataTable As DataTable Dim sconnection As String Try sconnection = mConnectionString objAdapter = New OdbcDataAdapter objCon = New OdbcConnection(sconnection) objCon.Open() objAdapter.SelectCommand = cmdCommand objAdapter.SelectCommand.Connection = objCon objAdapter.SelectCommand.CommandType = CommandType.StoredProcedure objAdapter.SelectCommand.CommandTimeout = Globals.mReportTimeOut If Not mIsOracle Then objAdapter.SelectCommand.CommandText = String.Format("{{call {0}}}", spName) Else Dim returnValue As New OdbcParameter returnValue.Direction = ParameterDirection.Output returnValue.ParameterName = "@Vret_val" returnValue.OdbcType = OdbcType.Numeric objAdapter.SelectCommand.Parameters.Add(returnValue) objAdapter.SelectCommand.CommandText = String.Format("{{call {0}(?)}}", spName) End If Try objDataTable = New DataTable(spName) objAdapter.Fill(objDataTable) Catch ex As Exception ... Question: I am puzzled as to what String.Format("{{call {0}(?)}}", spName) does, in particular the (?) part. My understanding of the String.Format is that it will simply replace {0} with spName. The {{, }}, and (?) do throw me off because { reminds me of formatting, (?) hints at some advanced regex use. Unfortunately I am getting little help from a key person who is on vacation without a leash [smart]phone. I am guessing that I simply add 5 more lines for each additional parameter, and change String.Format("{{call {0}(?)}}", spName) to String.Format("{{call {0}(?,?,?)}}", spName). I forgot to mention that I am coding this "blindly" - I have a compiler to help me, but no environment set up to test this. This will be over in a few days, but I need to do my best to try finishing it on time :) Thanks.

    Read the article

  • ASP.NET SqlDataReader throwing error: Invalid attempt to call Read when reader is closed.

    - by Bugget
    This one has me stumped. Here are the relative bits of code: public AgencyDetails(Guid AgencyId) { try { evgStoredProcedure Procedure = new evgStoredProcedure(); Hashtable commandParameters = new Hashtable(); commandParameters.Add("@AgencyId", AgencyId); SqlDataReader AppReader = Procedure.ExecuteReaderProcedure("evg_getAgencyDetails", commandParameters); commandParameters.Clear(); //The following line is where the error is thrown. Errormessage: Invalid attempt to call Read when reader is closed. while (AppReader.Read()) { AgencyName = AppReader.GetOrdinal("AgencyName").ToString(); AgencyAddress = AppReader.GetOrdinal("AgencyAddress").ToString(); AgencyCity = AppReader.GetOrdinal("AgencyCity").ToString(); AgencyState = AppReader.GetOrdinal("AgencyState").ToString(); AgencyZip = AppReader.GetOrdinal("AgencyZip").ToString(); AgencyPhone = AppReader.GetOrdinal("AgencyPhone").ToString(); AgencyFax = AppReader.GetOrdinal("AgencyFax").ToString(); } AppReader.Close(); AppReader.Dispose(); } catch (Exception ex) { throw new Exception("AgencyDetails Constructor: " + ex.Message.ToString()); } } And the implementation of ExecuteReaderProcedure: public SqlDataReader ExecuteReaderProcedure(string ProcedureName, Hashtable Parameters) { SqlDataReader returnReader; using (SqlConnection conn = new SqlConnection(connectionString)) { try { SqlCommand cmd = new SqlCommand(ProcedureName, conn); SqlParameter param = new SqlParameter(); cmd.CommandType = System.Data.CommandType.StoredProcedure; foreach (DictionaryEntry keyValue in Parameters) { cmd.Parameters.AddWithValue(keyValue.Key.ToString(), keyValue.Value); } conn.Open(); returnReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); } catch (SqlException e) { throw new Exception(e.Message.ToString()); } } return returnReader; } The connection string is working as other stored procedures in the same class run fine. The only problem seems to be when returning SqlDataReaders from this method! They throw the error message in the title. Any ideas are greatly appreciated! Thanks in advance!

    Read the article

  • how can i learn Enterprise library 4.0 ?

    - by ykaratoprak
    I try to learn Enterprise Library. i find these useful codes to get data from sql. But i try to send data via parameter. also use UPDATE, DELETE, SAVe method. Do you give sama sample? i'm using enterprise 4.0 !!! using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using Microsoft.Practices.EnterpriseLibrary.Common; using Microsoft.Practices.EnterpriseLibrary.Data; namespace WebApplicationForEnterpirires { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Database objdbase = DatabaseFactory.CreateDatabase("connectionString"); DataSet ds = objdbase.ExecuteDataSet(CommandType.StoredProcedure, "sp_GetProducts"); GridView1.DataSource = ds; GridView1.DataBind(); } } }

    Read the article

  • Building Stored Procedure to group data into ranges with roughly equal results in each bucket

    - by Len
    I am trying to build one procedure to take a large amount of data and create 5 range buckets to display the data. the buckets ranges will have to be set according to the results. Here is my existing SP GO /****** Object: StoredProcedure [dbo].[sp_GetRangeCounts] Script Date: 03/28/2010 19:50:45 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[sp_GetRangeCounts] @idMenu int AS declare @myMin decimal(19,2), @myMax decimal(19,2), @myDif decimal(19,2), @range1 decimal(19,2), @range2 decimal(19,2), @range3 decimal(19,2), @range4 decimal(19,2), @range5 decimal(19,2), @range6 decimal(19,2) SELECT @myMin=Min(modelpropvalue), @myMax=Max(modelpropvalue) FROM xmodelpropertyvalues where modelPropUnitDescriptionID=@idMenu set @myDif=(@myMax-@myMin)/5 set @range1=@myMin set @range2=@myMin+@myDif set @range3=@range2+@myDif set @range4=@range3+@myDif set @range5=@range4+@myDif set @range6=@range5+@myDif select @myMin,@myMax,@myDif,@range1,@range2,@range3,@range4,@range5,@range6 select t.range as myRange, count(*) as myCount from ( select case when modelpropvalue between @range1 and @range2 then 'range1' when modelpropvalue between @range2 and @range3 then 'range2' when modelpropvalue between @range3 and @range4 then 'range3' when modelpropvalue between @range4 and @range5 then 'range4' when modelpropvalue between @range5 and @range6 then 'range5' end as range from xmodelpropertyvalues where modelpropunitDescriptionID=@idmenu) t group by t.range order by t.range This calculates the min and max value from my table, works out the difference between the two and creates 5 buckets. The problem is that if there are a small amount of very high (or very low) values then the buckets will appear very distorted - as in these results... range1 2806 range2 296 range3 75 range5 1 Basically I want to rebuild the SP so it creates buckets with equal amounts of results in each. I have played around with some of the following approaches without quite nailing it... SELECT modelpropvalue, NTILE(5) OVER (ORDER BY modelpropvalue) FROM xmodelpropertyvalues - this creates a new column with either 1,2,3,4 or 5 in it ROW_NUMBER()OVER (ORDER BY modelpropvalue) between @range1 and @range2 ROW_NUMBER()OVER (ORDER BY modelpropvalue) between @range2 and @range3 or maybe i could allocate every record a row number then divide into ranges from this?

    Read the article

  • Catching specific vs. generic exceptions in c#

    - by Scott Vercuski
    This question comes from a code analysis run against an object I've created. The analysis says that I should catch a more specific exception type than just the basic Exception. Do you find yourself using just catching the generic Exception or attempting to catch a specific Exception and defaulting to a generic Exception using multiple catch blocks? One of the code chunks in question is below: internal static bool ClearFlags(string connectionString, Guid ID) { bool returnValue = false; SqlConnection dbEngine = new SqlConnection(connectionString); SqlCommand dbCmd = new SqlCommand("ClearFlags", dbEngine); SqlDataAdapter dataAdapter = new SqlDataAdapter(dbCmd); dbCmd.CommandType = CommandType.StoredProcedure; try { dbCmd.Parameters.AddWithValue("@ID", ID.ToString()); dbEngine.Open(); dbCmd.ExecuteNonQuery(); dbEngine.Close(); returnValue = true; } catch (Exception ex) { ErrorHandler(ex); } return returnValue; } Thank you for your advice EDIT: Here is the warning from the code analysis Warning 351 CA1031 : Microsoft.Design : Modify 'ClearFlags(string, Guid)' to catch a more specific exception than 'Exception' or rethrow the exception

    Read the article

  • How to send check boxes ID in gridview in one string for mass update.

    - by SmartDev
    hi , I have a grid which has check boxes and when selecting the top chek box select all will select all the check box in gridview and would update .for this im using for loop where it exceutes every time and this is taking lot of time cuase there are more thn 100 records in grid . try { string StrOutputMessageDisplayDocReqCsu = string.Empty; string strid = string.Empty; string strflag = string.Empty; string strSelected = string.Empty; for (int j = 0; j < GdvDocReqMU.Rows.Count; j++) { CheckBox Chkupdate = (CheckBox)GdvDocReqMU.Rows[j].Cells[1].FindControl("chkDR"); if (Chkupdate != null) { if (Chkupdate.Checked) { strid = ((Label)GdvDocReqMU.Rows[j].FindControl("lblIDDocReqCsu")).Text; strflag = ((Label)GdvDocReqMU.Rows[j].FindControl("lblStatusDocReqCsu")).Text; cmd = new SqlCommand("sp_Update_v1", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@id", strSelected); cmd.Parameters.AddWithValue("@flag", DdlStatusDocReqMU.SelectedValue); cmd.Parameters.AddWithValue("@notes", txtnotesDocReqMU.Text); cmd.Parameters.AddWithValue("@user", strUseridDRAhk); cmd.Parameters.Add(new SqlParameter("@message", SqlDbType.VarChar, 100, ParameterDirection.Output, false, 0, 50, "message", DataRowVersion.Default, null)); cmd.UpdatedRowSource = UpdateRowSource.OutputParameters; con.Open(); cmd.ExecuteNonQuery(); con.Close(); } } } //} //StrOutputMessageDisplayDocReqCsu += (string)cmd.Parameters["@message"].Value + "<br/>"; //lbldbmessDocReqAhk.Text += StrOutputMessageDisplayDocReqCsu + "<br>"; GetgridDocReq(); } catch (Exception ex) { lbldbmessDocReqAhk.Text = ex.Message.ToString(); }

    Read the article

  • error invoking store procedure with input parameter from ADO.Net

    - by George2
    Hello everyone, I am using VSTS 2008 + C# + .Net 3.5 + ADO.Net. Here is my code and related error message. The error message says, @Param1 is not supplied, but actually it is supplied in my code. Any ideas what is wrong? System.Data.SqlClient.SqlException: Procedure or function 'Pr_Foo' expects parameter '@Param1', which was not supplied. class Program { private static SqlCommand _command; private static SqlConnection connection; private static readonly string _storedProcedureName = "Pr_Foo"; private static readonly string connectionString = "server=.;integrated Security=sspi;initial catalog=FooDB"; public static void Prepare() { connection = new SqlConnection(connectionString); connection.Open(); _command = connection.CreateCommand(); _command.CommandText = _storedProcedureName; _command.CommandType = CommandType.StoredProcedure; } public static void Dispose() { connection.Close(); } public static void Run() { try { SqlParameter Param1 = _command.Parameters.Add("@Param1", SqlDbType.Int, 300101); Param1.Direction = ParameterDirection.Input; SqlParameter Param2 = _command.Parameters.Add("@Param2", SqlDbType.Int, 100); portal_SiteInfoID.Direction = ParameterDirection.Input; SqlParameter Param3 = _command.Parameters.Add("@Param3", SqlDbType.Int, 200); portal_RoleInfoID.Direction = ParameterDirection.Input; _command.ExecuteScalar(); } catch (Exception e) { Console.WriteLine(e); } } static void Main(string[] args) { try { Prepare(); Thread t1 = new Thread(Program.Run); t1.Start(); t1.Join(); Dispose(); } catch (Exception ex) { Console.WriteLine(ex.Message + "\t" + ex.StackTrace); } } } thanks in avdance, George

    Read the article

  • Insert Stored Procedure does not Create Database Record

    - by SidC
    Hello All, I have the following stored procedure: ALTER PROCEDURE Pro_members_Insert @id int outPut, @LoginName nvarchar(50), @Password nvarchar(15), @FirstName nvarchar(100), @LastName nvarchar(100), @signupDate smalldatetime, @Company nvarchar(100), @Phone nvarchar(50), @Email nvarchar(150), @Address nvarchar(255), @PostalCode nvarchar(10), @State_Province nvarchar(100), @City nvarchar(50), @countryCode nvarchar(4), @active bit, @activationCode nvarchar(50) AS declare @usName as varchar(50) set @usName='' select @usName=isnull(LoginName,'') from members where LoginName=@LoginName if @usName <> '' begin set @ID=-3 RAISERROR('User Already exist.', 16, 1) return end set @usName='' select @usName=isnull(email,'') from members where Email=@Email if @usName <> '' begin set @ID=-4 RAISERROR('Email Already exist.', 16, 1) return end declare @MemID as int select @memID=isnull(max(ID),0)+1 from members INSERT INTO members ( id, LoginName, Password, FirstName, LastName, signupDate, Company, Phone, Email, Address, PostalCode, State_Province, City, countryCode, active,activationCode) VALUES ( @Memid, @LoginName, @Password, @FirstName, @LastName, @signupDate, @Company, @Phone, @Email, @Address, @PostalCode, @State_Province, @City, @countryCode, @active,@activationCode) if @@error <> 0 set @ID=-1 else set @id=@memID Note that I've "inherited" this sproc and the database. I am trying to insert a new record from my signup.aspx page. My SQLDataSource is as follows: <asp:SqlDataSource runat="server" ID="dsAddMember" ConnectionString="rmsdbuser" InsertCommandType="StoredProcedure" InsertCommand="Pro_members_Insert" ProviderName="System.Data.SqlClient"> The click handler for btnSave is as follows: Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click Try dsAddMember.DataBind() Catch ex As Exception End Try End Sub When I run this page, signup.aspx, provide required fields and click submit, the page simply reloads and the database table does not reflect the newly-inserted record. Questions: 1. How do I catch the error messages that might be returned from the sproc? 2. Please advise how to change signup.aspx so that the insert occurs. Thanks, Sid

    Read the article

  • Database.ExecuteNonQuery does not return

    - by dan-waterbly
    I have a very odd issue. When I execute a specific database stored procedure from C# using SqlCommand.ExecuteNonQuery, my stored procedure is never executed. Furthermore, SQL Profiler does not register the command at all. I do not receive a command timeout, and no exeception is thrown. The weirdest thing is that this code has worked fine over 1,200,000 times, but for this one particular file I am inserting into the database, it just hangs forever. When I kill the application, I receive this error in the event log of the database server: "A fatal error occurued while reading the input stream from the network. The session will be terminated (input error: 64, output error: 0). Which makes me think that the database server is receiving the command, though SQL Profiler says otherwise. I know that the appropiate permissions are set, and that the connection string is right as this piece of code and stored procedure works fine with other files. Below is the code that calls the stored procedure, it may be important to note that the file I am trying to insert is 33.5MB, but I have added more than 10,000 files larger than 500MB, so I do not think the size is the issue: using (SqlConnection sqlconn = new SqlConnection(ConfigurationManager.ConnectionStrings["TheDatabase"].ConnectionString)) using (SqlCommand command = sqlconn.CreateCommand()) { command.CommandText = "Add_File"; command.CommandType = CommandType.StoredProcedure; command.CommandTimeout = 30 //should timeout in 30 seconds, but doesn't... command.Parameters.AddWithValue("@ID", ID).SqlDbType = SqlDbType.BigInt; command.Parameters.AddWithValue("@BinaryData", byteArr).SqlDbType = SqlDbType.VarBinary; command.Parameters.AddWithValue("@FileName", fileName).SqlDbType = SqlDbType.VarChar; sqlconn.Open(); command.ExecuteNonQuery(); } There is no firewall between the server making the call and the database server, and the windows firewalls have been disabled to troubleshoot this issue.

    Read the article

  • using a stored procedure for login in c#

    - by Jin Yim
    Hi all, If I run a store procedure with two parameter values (admin, admin) (parameters : admin, admin) I get the following message : Session_UID User_Group_Name Sys_User_Name NULLAdministratorsNTMSAdmin No rows affected. (1 row(s) returned) @RETURN_VALUE = 0 Finished running [dbo].[p_SYS_Login]. -- To get the same message in c# I used the code following : string strConnection = Settings.Default.ConnectionString; using (SqlConnection conn = new SqlConnection(strConnection)) { using (SqlCommand cmd = new SqlCommand()) { SqlDataReader rdr = null; cmd.Connection = conn; cmd.CommandText = "p_SYS_Login"; cmd.CommandType = CommandType.StoredProcedure; SqlParameter paramReturnValue = new SqlParameter(); paramReturnValue.ParameterName = "@RETURN_VALUE"; paramReturnValue.SqlDbType = SqlDbType.Int; paramReturnValue.SourceColumn = null; paramReturnValue.Direction = ParameterDirection.ReturnValue; cmd.Parameters.Add(paramReturnValue); cmd.Parameters.Add(paramGroupName); cmd.Parameters.Add(paramUserName); cmd.Parameters.AddWithValue("@Sys_Login", "admin"); cmd.Parameters.AddWithValue("@Sys_Password", "admin"); try { conn.Open(); rdr = cmd.ExecuteReader(); string test = (string)cmd.Parameters["@RETURN_VALUE"].Value; while (rdr.Read()) { Console.WriteLine("test : " + rdr[0]); } } catch (Exception ex) { string message = ex.Message; string caption = "MAVIS Exception"; MessageBoxButtons buttons = MessageBoxButtons.OK; MessageBox.Show( message, caption, buttons, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1); } finally { cmd.Dispose(); conn.Close(); } } } but I get nothing in SqlDataReader rdr ; is there something I am missing ? Thanks

    Read the article

  • Populate asp.net MVC Index page with data from the database

    - by Sunil Ramu
    I have a web application in which I need to fetch data from the database and display in the index page. As you know, asp.net mvc has given options to edit delete etc... I need to populate the page using the conventional DB way and it uses a stored procedure to retrieve results. I dont want to use LINQ. This is my model entity class using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace LogMVCApp.Models { public class Property { public int Id { get; set; } public string LogInId { get; set; } public string Username { get; set; } public string Action { get; set; } public string Information { get; set; } public bool Passed{get; set; } public string LogType { get; set; } } } and I need to retrieve data using something like this... var conString = ConfigurationManager.ConnectionStrings["connection"].ToString(); var conn = new SqlConnection(conString); var command = new SqlCommand("LogInsert", conn){CommandType=CommandType.StoredProcedure};

    Read the article

  • Can I dispose a DataTable and still use its data later?

    - by Eduardo León
    Noob ADO.NET question: Can I do the following? Retrieve a DataTable somehow. Dispose it. Still use its data. (But not send it back to the database, or request the database to update it.) I have the following function, which is indirectly called by every WebMethod in a Web Service of mine: public static DataTable GetDataTable(string cmdText, SqlParameter[] parameters) { // Read the connection string from the web.config file. Configuration configuration = WebConfigurationManager.OpenWebConfiguration("/WSProveedores"); ConnectionStringSettings connectionString = configuration.ConnectionStrings.ConnectionStrings["..."]; SqlConnection connection = null; SqlCommand command = null; SqlParameterCollection parameterCollection = null; SqlDataAdapter dataAdapter = null; DataTable dataTable = null; try { // Open a connection to the database. connection = new SqlConnection(connectionString.ConnectionString); connection.Open(); // Specify the stored procedure call and its parameters. command = new SqlCommand(cmdText, connection); command.CommandType = CommandType.StoredProcedure; parameterCollection = command.Parameters; foreach (SqlParameter parameter in parameters) parameterCollection.Add(parameter); // Execute the stored procedure and retrieve the results in a table. dataAdapter = new SqlDataAdapter(command); dataTable = new DataTable(); dataAdapter.Fill(dataTable); } finally { if (connection != null) { if (command != null) { if (dataAdapter != null) { // Here the DataTable gets disposed. if (dataTable != null) dataTable.Dispose(); dataAdapter.Dispose(); } parameterCollection.Clear(); command.Dispose(); } if (connection.State != ConnectionState.Closed) connection.Close(); connection.Dispose(); } } // However, I still return the DataTable // as if nothing had happened. return dataTable; }

    Read the article

  • How do I access Dictionary items?

    - by salvationishere
    I am developing a C# VS2008 / SQL Server website app and am new to the Dictionary class. Can you please advise on best method of accomplishing this? Here is a code snippet: SqlConnection conn2 = new SqlConnection(connString); SqlCommand cmd = conn2.CreateCommand(); cmd.CommandText = "dbo.AppendDataCT"; cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = conn2; SqlParameter p1, p2, p3; foreach (string s in dt.Rows[1].ItemArray) { DataRow dr = dt.Rows[1]; // second row p1 = cmd.Parameters.AddWithValue((string)dic[0], (string)dr[0]); p1.SqlDbType = SqlDbType.VarChar; p2 = cmd.Parameters.AddWithValue((string)dic[1], (string)dr[1]); p2.SqlDbType = SqlDbType.VarChar; p3 = cmd.Parameters.AddWithValue((string)dic[2], (string)dr[2]); p3.SqlDbType = SqlDbType.VarChar; } but this is giving me compiler error: The best overloaded method match for 'System.Collections.Generic.Dictionary<string,string>.this[string]' has some invalid arguments I just want to access each value from "dic" and load into these SQL parameters. How do I do this? Do I have to enter the key? The keys are named "col1", "col2", etc., so not the most user-friendly. Any other tips? Thanks!

    Read the article

  • Stored Procedure Parameters Not Available After Declared

    - by SidC
    Hi All, Pasted below is a stored procedure written in SQL Server 2005. My intent is to call this sproc from my ASP.NEt web application through the use of a wizard control. I am new to SQL Server and especially to stored procedures. I'm unsure why my parameters are not available to the web application and not visible in SSMS treeview as a parameter under my sproc name. Can you help me correct the sproc below so that the parameters are correctly instantiated and available for use in my web application? Thanks, Sid Stored Procedure syntax: USE [Diel_inventory] GO /****** Object: StoredProcedure [dbo].[AddQuote] Script Date: 05/09/2010 00:31:10 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER procedure [dbo].[AddQuote] as Declare @CustID int, @CompanyName nvarchar(50), @Address nvarchar(50), @City nvarchar(50), @State nvarchar(2), @ZipCode nvarchar(5), @Phone nvarchar(12), @FAX nvarchar(12), @Email nvarchar(50), @ContactName nvarchar(50), @QuoteID int, @QuoteDate datetime, @NeedbyDate datetime, @QuoteAmt decimal, @ID int, @QuoteDetailPartID int, @PartNumber float, @Quantity int begin Insert into dbo.Customers (CompanyName, Address, City, State, ZipCode, OfficePhone, OfficeFAX, Email, PrimaryContactName) Values (@CompanyName, @Address, @City, @State, @ZipCode, @Phone, @FAX, @Email, @ContactName) set @CustID = scope_identity() Insert into dbo.Quotes (fkCustomerID,NeedbyDate,QuoteAmt) Values(@CustID,@NeedbyDate,@QuoteAmt) set @QuoteID = scope_identity() Insert into dbo.QuoteDetail (ID) values(@ID) set @ID=scope_identity() Insert into dbo.QuoteDetailParts (QuoteDetailPartID, QuoteDetailID, PartNumber, Quantity) values (@ID, @QuoteDetailPartID, @PartNumber, @Quantity) END

    Read the article

  • Procedure expects parameter which was not supplied.

    - by Tony Peterson
    I'm getting the error when accessing a Stored Procedure in SQL Server Server Error in '/' Application. Procedure or function 'ColumnSeek' expects parameter '@template', which was not supplied. This is happening when I call a Stored Procedure with a parameter through .net's data connection to sql (System.data.SqlClient), even though I am supplying the parameter. Here is my code. SqlConnection sqlConn = new SqlConnection(connPath); sqlConn.Open(); // METADATA RETRIEVAL string sqlCommString = "QCApp.dbo.ColumnSeek"; SqlCommand metaDataComm = new SqlCommand(sqlCommString, sqlConn); metaDataComm.CommandType = CommandType.StoredProcedure; SqlParameter sp = metaDataComm.Parameters.Add("@template", SqlDbType.VarChar, 50); sp.Value = Template; SqlDataReader metadr = metaDataComm.ExecuteReader(); And my Stored Procedure is: USE [QCApp] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[ColumnSeek] @template varchar(50) AS EXEC('SELECT Column_Name, Data_Type FROM [QCApp].[INFORMATION_SCHEMA].[COLUMNS] WHERE TABLE_NAME = ' + @template); I'm trying to figure out what I'm doing wrong here. Edit: As it turns out, Template was null because I was getting its value from a parameter passed through the URL and I screwed up the url param passing (I was using @ for and instead of &)

    Read the article

  • asp.net stored procedure problem

    - by kenom
    Why this code don't work,when i want run this code vwd 2008 express show me this error message:Invalid object name 'answers'. this is my ascx.cs code: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.Security; using System.Data.SqlClient; using System.Configuration; public partial class odgl : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { string connectionString = @"SANATIZEDSTRING!!!!"; using (SqlConnection cn = new SqlConnection(connectionString)) { using (SqlCommand dohvati = new SqlCommand("dbo.get_answers",cn)) { dohvati.CommandType = CommandType.StoredProcedure; SqlParameter izracun = new SqlParameter("@count", SqlDbType.Int); izracun.Direction = ParameterDirection.Output; dohvati.Parameters.Add(izracun); cn.Open(); dohvati.ExecuteNonQuery(); int count = Int32.Parse(dohvati.Parameters["@count"].Value.ToString()); Response.Write(count.ToString()); cn.Close(); } } } } and this is my stored procedure : set ANSI_NULLS ON set QUOTED_IDENTIFIER ON GO ALTER procedure [dbo].[get_answers] @ukupno int output as select @count= (SELECT COUNT(*) FROM answers) go

    Read the article

  • Call Oracle package function using Odbc from C#

    - by Paolo Tedesco
    I have a function defined inside an Oracle package: CREATE OR REPLACE PACKAGE BODY TESTUSER.TESTPKG as FUNCTION testfunc(n IN NUMBER) RETURN NUMBER as begin return n + 1; end testfunc; end testpkg; / How can I call it from C# using Odbc? I tried the following: using System; using System.Data; using System.Data.Odbc; class Program { static void Main(string[] args) { using (OdbcConnection connection = new OdbcConnection("DSN=testdb;UID=testuser;PWD=testpwd")) { connection.Open(); OdbcCommand command = new OdbcCommand("TESTUSER.TESTPKG.testfunc", connection); command.CommandType = System.Data.CommandType.StoredProcedure; command.Parameters.Add("ret", OdbcType.Int).Direction = ParameterDirection.ReturnValue; command.Parameters.Add("n", OdbcType.Int).Direction = ParameterDirection.Input; command.Parameters["n"].Value = 42; command.ExecuteNonQuery(); Console.WriteLine(command.Parameters["ret"].Value); } } } But I get an exception saying "Invalid SQL Statement". What am I doing wrong?

    Read the article

  • Conversion failed when converting datetime from character string

    - by salvationishere
    I am developing a C# VS 2008 / SQL Server 2005 Express website application. I have tried some of the fixes for this problem but my call stack differs from others. And these fixes did not fix my problem. What steps can I take to troubleshoot this? Here is my error: System.Data.SqlClient.SqlException was caught Message="Conversion failed when converting datetime from character string." Source=".Net SqlClient Data Provider" ErrorCode=-2146232060 LineNumber=10 Number=241 Procedure="AppendDataCT" Server="\\\\.\\pipe\\772EF469-84F1-43\\tsql\\query" State=1 StackTrace: at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at ADONET_namespace.ADONET_methods.AppendDataCT(DataTable dt, Dictionary`2 dic) in c:\Documents and Settings\Admin\My Documents\Visual Studio 2008\WebSites\Jerry\App_Code\ADONET methods.cs:line 102 And here is the related code. When I debugged this code, "dic" only looped through the 3 column names, but did not look into row values which are stored in "dt", the Data Table. public static string AppendDataCT(DataTable dt, Dictionary<string, string> dic) { if (dic.Count != 3) throw new ArgumentOutOfRangeException("dic can only have 3 parameters"); string connString = ConfigurationManager.ConnectionStrings["AW3_string"].ConnectionString; string errorMsg; try { using (SqlConnection conn2 = new SqlConnection(connString)) { using (SqlCommand cmd = conn2.CreateCommand()) { cmd.CommandText = "dbo.AppendDataCT"; cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = conn2; foreach (string s in dic.Keys) { SqlParameter p = cmd.Parameters.AddWithValue(s, dic[s]); p.SqlDbType = SqlDbType.VarChar; } conn2.Open(); cmd.ExecuteNonQuery(); conn2.Close(); errorMsg = "The Person.ContactType table was successfully updated!"; } } }

    Read the article

  • Database Programming in C#, returning output from Stored Proc

    - by jpavlov
    I am working at gaining an understanding at how to interface stored procedures with applications. My example is simple, but it doesn't display my columns and rows in the command prompt, instead it display System.Data.SqlClient.SqlDataReader. How do I display the rows from my stored procudure? ----Stored Proc-- ALTER PROCEDURE dbo.SelectID AS SELECT * FROM tb_User; ----- Below is the code: using System; using System.Data.SqlClient; using System.IO; namespace ExecuteStoredProc { class Program { static void Main(string[] args) { SqlConnection cnnUserMan; SqlCommand cmmUser; //SqlDataReader drdUser; //Instantiate and open the connection cnnUserMan = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=c:\\Program Files\\Microsoft SQL Server\\MSSQL10.SQLEXPRESS\\MSSQL\\DATA\\UserDB.mdf; Integrated Security=True;Connect Timeout=30;User Instance=True"); cnnUserMan.Open(); //Instantiate and initialize command cmmUser = new SqlCommand("SelectID", cnnUserMan); cmmUser.CommandType = System.Data.CommandType.StoredProcedure; //drdUser = cmmUser.ExecuteReader(); Console.WriteLine(cmmUser.ExecuteReader()); Console.ReadLine(); } } } Thanks.

    Read the article

  • Using block around a static/singleton resource reference

    - by byte
    This is interesting (to me anyway), and I'd like to see if anyone has a good answer and explanation for this behavior. Say you have a singleton database object (or static database object), and you have it stored in a class Foo. public class Foo { public static SqlConnection DBConn = new SqlConnection(ConfigurationManager.ConnectionStrings["BAR"].ConnectionString); } Then, lets say that you are cognizant of the usefulness of calling and disposing your connection (pretend for this example that its a one-time use for purposes of illustration). So you decide to use a 'using' block to take care of the Dispose() call. using (SqlConnection conn = Foo.DBConn) { conn.Open(); using (SqlCommand cmd = new SqlCommand()) { cmd.Connection = conn; cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.CommandText = "SP_YOUR_PROC"; cmd.ExecuteNonQuery(); } conn.Close(); } This fails, with an error stating that the "ConnectionString property is not initialized". It's not an issue with pulling the connection string from the app.config/web.config. When you investigate in a debug session you see that Foo.DBConn is not null, but contains empty properties. Why is this?

    Read the article

  • How to convert "0" and "1" to false and true

    - by Chris
    I have a method which is connecting to a database via Odbc. The stored procedure which I'm calling has a return value which from the database side is a 'Char'. Right now I'm grabbing that return value as a string and using it in a simple if statement. I really don't like the idea of comparing a string like this when only two values can come back from the database, 0 and 1. OdbcCommand fetchCommand = new OdbcCommand(storedProc, conn); fetchCommand.CommandType = CommandType.StoredProcedure; fetchCommand.Parameters.AddWithValue("@column ", myCustomParameter); fetchCommand.Parameters.Add("@myReturnValue", OdbcType.Char, 1). Direction = ParameterDirection.Output; fetchCommand.ExecuteNonQuery(); string returnValue = fetchCommand.Parameters["@myReturnValue"].Value.ToString(); if (returnValue == "1") { return true; } What would be the proper way to handle this situation. I've tried 'Convert.ToBoolean()' which seemed like the obvious answer but I ran into the 'String was not recognized as a valid Boolean. ' exception being thrown. Am I missing something here, or is there another way to make '1' and '0' act like true and false? Thanks!

    Read the article

  • How do I change or add data to a data repeater and get it to display in ASP.NET

    - by CowKingDeluxe
    Here is my code-behind, this adds the "OakTreeName" to the datarepeater. There's about 200 of them. Dim cmd As New SqlClient.SqlCommand("OakTree_Load", New SqlClient.SqlConnection(ConnStr)) cmd.CommandType = CommandType.StoredProcedure cmd.Connection.Open() Dim datareader As SqlClient.SqlDataReader = cmd.ExecuteReader() OakTree_Thumb_Repeater.DataSource = datareader OakTree_Thumb_Repeater.DataBind() cmd.Connection.Close() Here is essentially what I'd like to do with my markup: <ContentTemplate> <asp:Repeater ID="OakTree_Thumb_Repeater" runat="server"> <ItemTemplate> <asp:ImageButton ImageUrl="<%# Container.DataItem("OakTreeName") %>" AlternateText="" runat="server" /> <!-- Or I'd like to do it this way by adding a custom variable to the data repeater --> <asp:ImageButton ImageUrl="<%# Container.DataItem("OakTreeThumbURL") %>" AlternateText="" runat="server" /> </ItemTemplate> </asp:Repeater> </ContentTemplate> I would like to manipulate the "OakTreeName" variable before it gets placed into the item template. Basically I need to manipulate the "OakTreeName" variable and then input it as the ImageURL for the imagebutton within the item template. How do I do this? Am I approaching this wrong? Is there a way to manipulate the item template from code-behind before it gets displayed for each round of variables in the data repeater?

    Read the article

  • Get Multiple Values From Database ASP.NET/C#

    - by user1043177
    I am trying to get/return multiple values from an SQL-Server database using and display them on an ASP.NET page. I am using a stored procedure to perform the SELECT command on the Database side. I am able to return the first value that matches the variable @PERSON but only one row is returned each time. Any help would be much appreciated. Database handler class public MainSQL() { _productConn = new SqlConnection(); _productConnectionString += "data source=mssql.database.co.uk;InitialCatalog=test_data;User ID=username;Password=password"; _productConn.ConnectionString = _productConnectionString; } public string GetItemName(int PersonID) { string returnvalue = string.Empty; SqlCommand myCommand = new SqlCommand("GetItem", _productConn); myCommand.CommandType = CommandType.StoredProcedure; myCommand.Parameters.Add(new SqlParameter("@PERSON", SqlDbType.Int)); myCommand.Parameters[0].Value = PersonID; _productConn.Open(); returnvalue = (string)myCommand.ExecuteScalar(); _productConn.Close(); return (string)returnvalue; } Stored Procedure USE [test_data] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [ppir].[GetItem] ( @PERSON int ) AS /*SET NOCOUNT ON;*/ SELECT Description FROM [Items] WHERE PersonID = @PERSON RETURN return.aspx namespace test { public partial class Final_Page : System.Web.UI.Page { MainSQL GetInfo; protected void Page_Load(object sender, EventArgs e) { int PersonId = (int)Session["PersonID"]; GetInfo = new MainSQL(); string itemname = GetInfo.GetItemName(PersonId); ReturnItemName.Text = itemname; } // End Page_Load } // End Class } // End Namespace

    Read the article

  • Stored procedure or function expects parameter which is not supplied

    - by user2920046
    I am trying to insert data into a SQL Server database by calling a stored procedure, but I am getting the error Procedure or function 'SHOWuser' expects parameter '@userID', which was not supplied. My stored procedure is called "SHOWuser". I have checked it thoroughly and no parameters is missing. My code is: public void SHOWuser(string userName, string password, string emailAddress, List preferences) { SqlConnection dbcon = new SqlConnection(conn); try { SqlCommand cmd = new SqlCommand(); cmd.Connection = dbcon; cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.CommandText = "SHOWuser"; cmd.Parameters.AddWithValue("@userName", userName); cmd.Parameters.AddWithValue("@password", password); cmd.Parameters.AddWithValue("@emailAddress", emailAddress); dbcon.Open(); int i = Convert.ToInt32(cmd.ExecuteScalar()); cmd.Parameters.Clear(); cmd.CommandText = "tbl_pref"; foreach (int preference in preferences) { cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("@userID", Convert.ToInt32(i)); cmd.Parameters.AddWithValue("@preferenceID", Convert.ToInt32(preference)); cmd.ExecuteNonQuery(); } } catch (Exception) { throw; } finally { dbcon.Close(); } and the stored procedure is: ALTER PROCEDURE [dbo].[SHOWuser] -- Add the parameters for the stored procedure here ( @userName varchar(50), @password nvarchar(50), @emailAddress nvarchar(50) ) AS BEGIN INSERT INTO tbl_user(userName,password,emailAddress) values(@userName,@password,@emailAddress) select tbl_user.userID,tbl_user.userName,tbl_user.password,tbl_user.emailAddress, stuff((select ',' + preferenceName from tbl_pref_master inner join tbl_preferences on tbl_pref_master.preferenceID = tbl_preferences.preferenceID where tbl_preferences.userID=tbl_user.userID FOR XML PATH ('')),1,1,' ' ) AS Preferences from tbl_user SELECT SCOPE_IDENTITY(); END Pls help, Thankx in advance...

    Read the article

  • How to pass XML from C# to a stored procedure in SQL Server 2008?

    - by Geetha
    I want to pass xml document to sql server stored procedure such as this: CREATE PROCEDURE BookDetails_Insert (@xml xml) I want compare some field data with other table data and if it is matching that records has to inserted in to the table. Requirements: How do I pass XML to the stored procedure? I tried this, but it doesn’t work:[Working] command.Parameters.Add( new SqlParameter("@xml", SqlDbType.Xml) { Value = new SqlXml(new XmlTextReader(xmlToSave.InnerXml, XmlNodeType.Document, null)) }); How do I access the XML data within the stored procedure? Edit: [Working] String sql = "BookDetails_Insert"; XmlDocument xmlToSave = new XmlDocument(); xmlToSave.Load("C:\\Documents and Settings\\Desktop\\XML_Report\\Books_1.xml"); SqlConnection sqlCon = new SqlConnection("..."); using (DbCommand command = sqlCon.CreateCommand()) { **command.CommandType = CommandType.StoredProcedure;** command.CommandText = sql; command.Parameters.Add( new SqlParameter("@xml", SqlDbType.Xml) { Value = new SqlXml(new XmlTextReader(xmlToSave.InnerXml , XmlNodeType.Document, null)) }); sqlCon.Open(); DbTransaction trans = sqlCon.BeginTransaction(); command.Transaction = trans; try { command.ExecuteNonQuery(); trans.Commit(); sqlCon.Close(); } catch (Exception) { trans.Rollback(); sqlCon.Close(); throw; } Edit 2: How to create a select query to select pages, description based on some conditions. <booksdetail> <isn_13>700001048</isbn_13> <isn_10>01048B</isbn_10> <Image_URL>http://www.landt.com/Books/large/00/7010000048.jpg</Image_URL> <title>QUICK AND FLUPKE</title> <Description> PRANKS AND JOKES QUICK AND FLUPKE </Description> </booksdetail>

    Read the article

< Previous Page | 2 3 4 5 6 7 8  | Next Page >