![]() |
Модераторы: diadiavova, gambit |
![]() ![]() ![]() |
|
starley440 |
|
|||
Новичок Профиль Группа: Участник Сообщений: 8 Регистрация: 2.10.2004 Где: Питер Репутация: нет Всего: нет |
Суть проблемы вот в чём:
Есть база на SQL. В ней есть процедурка на выполнение запроса с параметрами. В SQL куэри анелайзере пишется запрос не больше не меньше как dbo.Procedure_name параметр Создал даже Script1 (см. выше) в проекте, который успешно в дебаг-окне показывает результат... Только никак не могу передать параметр этому скрипту... Грубо говоря, я даже не могу запустить выполнение этого скрипта внутри проекта...даже с ошибкой. Помогите пожалуйста... Как запустить скрипт ![]() Спасибо |
|||
|
||||
Vit |
|
|||
![]() Vitaly Nevzorov ![]() ![]() ![]() ![]() Профиль Группа: Экс. модератор Сообщений: 10964 Регистрация: 25.3.2002 Где: Chicago Репутация: нет Всего: 207 |
Перемещено в VB.Net
-------------------- With the best wishes, Vit I have done so much with so little for so long that I am now qualified to do anything with nothing Самый большой Delphi FAQ на русском языке здесь: www.drkb.ru |
|||
|
||||
Gazon |
|
|||
![]() Шустрый ![]() Профиль Группа: Участник Сообщений: 128 Регистрация: 9.1.2005 Репутация: 1 Всего: 8 |
Calling a Stored Procedure
Let's say we have a stored procedure that can return a row of data. Here's an example of a SQL Server stored procedure designed to do just that: CREATE PROCEDURE GetCustomer (@CustomerID nchar(5)) AS SELECT CustomerID, CompanyName, ContactName, ContactTitle FROM Customers WHERE CustomerID = @CustomerID RETURN Some databases, such as Oracle, cannot return a result set from a stored procedure call in this fashion. For more information on fetching a result set from an Oracle stored procedure using ADO.NET, please see the Microsoft Knowledge Base. How do we call this stored procedure from a Command? One option is to use the Command object's CommandType property. You can set this property to any value in the CommandType enumeration: Text, TableDirect, or StoredProcedure. The property is set to Text by default. Setting CommandType to StoredProcedure tells the Command that you're calling a stored procedure. The Command object will combine the value stored in its CommandText property with the information in its Parameters collection to generate the syntax to call your stored procedure, as shown here: Visual Basic .NET ... Dim cn As New OleDbConnection(strConn) cn.Open() Dim cmd As OleDbCommand = cn.CreateCommand() With cmd .CommandText = "GetCustomer" .CommandType = CommandType.StoredProcedure .Parameters.Add("@CustomerID", OleDbType.WChar, 5) .Parameters(0).Value = "ALFKI" End With Dim rdr As OleDbDataReader = cmd.ExecuteReader() If rdr.Read() Then Console.WriteLine(rdr("CompanyName")) Else Console.WriteLine("No customer found") End If rdr.Close() cn.Close() Visual C# .NET ... OleDbConnection cn = new OleDbConnection(strConn); cn.Open(); OleDbCommand cmd = cn.CreateCommand(); cmd.CommandText = "GetCustomer"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@CustomerID", OleDbType.WChar, 5); cmd.Parameters[0].Value = "ALFKI"; OleDbDataReader rdr = cmd.ExecuteReader(); if (rdr.Read()) Console.WriteLine(rdr["CompanyName"]); else Console.WriteLine("No customer found"); rdr.Close(); cn.Close(); The standard way to call the stored procedure is to use the following syntax: {? = CALL MyStoredProc(?, ?, ?)} The initial parameter marker represents the return value of the procedure call and can be omitted if you're not going to use the value returned. Leaving off the return parameter changes the query's syntax to this: {CALL GetCustomer(?)} I prefer using this syntax in my code rather than relying on the CommandType property. If you want to query a table, view, or stored procedure that contains odd characters such as spaces in its name, you must surround the object name with delimiters. With an OleDbCommand object, setting the CommandType property to TableDirect or StoredProcedure doesn't surround the object name with delimiters in such cases. You need to add the delimiters yourself. This behavior is not consistent for all Command objects. For example, the SqlCommand object will correctly delimit object names automatically. Of course, if you don't put spaces in your table and stored procedure names, this won't be an issue for you (nudge, nudge). My advice is to avoid relying on the CommandType property and instead use the appropriate syntax for your query in the CommandText property, as shown here: Visual Basic .NET Dim cmd As New OleDbDataAdapter() cmd.CommandText = "{CALL GetCustomer(?)}" cmd.CommandType = CommandType.Text Visual C# .NET OleDbDataAdapter cmd = new OleDbDataAdapter(); cmd.CommandText = "{CALL GetCustomer(?)}"; cmd.CommandType = CommandType.Text; Developers with some SQL Server experience might be used to using the EXEC syntax for calling stored procedures in tools such as Query Analyzer. You're welcome to use this syntax with your Command objects, but keep in mind that not all databases support this syntax. You might need to change your syntax slightly if you need to query a different type of database. Retrieving Data from Output Parameters Not all stored procedures return information through a result set. Many procedures return information through output parameters. Let's say our SQL Server GetCustomer stored procedure looks like the following instead: CREATE PROCEDURE GetCustomer (@CustomerID nchar(5), @CompanyName nvarchar(40) OUTPUT, @ContactName nvarchar(30) OUTPUT, @ContactTitle nvarchar(30) OUTPUT) AS SELECT @CompanyName = CompanyName, @ContactName = ContactName, @ContactTitle = ContactTitle FROM Customers WHERE CustomerID = @CustomerID IF @@ROWCOUNT = 1 RETURN 0 ELSE RETURN -1 How can we use a Command to retrieve data from the output parameters? The Parameter object has a Direction property that accepts values from the ParameterDirection enumeration: ReturnValue, Input, InputOutput, and Output. The default for the property is Input. In order to retrieve information from this stored procedure, we need to set the Direction property on the parameters that aren't input-only. The stored procedure uses the return parameter to indicate success or failure. So, in our code snippet we'll examine the value of the return parameter to determine whether we successfully located the desired customer in the table: Visual Basic .NET ... Dim cn As New OleDbConnection(strConn) cn.Open() Dim cmd As OleDbCommand = cn.CreateCommand() With cmd .CommandText = "{? = CALL GetCustomer(?, ?, ?, ?)}" .Parameters.Add("@RetVal", OleDbType.Integer) .Parameters.Add("@CustomerID", OleDbType.WChar, 5) .Parameters.Add("@CompanyName", OleDbType.VarWChar, 40) .Parameters.Add("@ContactName", OleDbType.VarWChar, 30) .Parameters.Add("@ContactTitle", OleDbType.VarWChar, 30) .Parameters("@ContactTitle").Direction = ParameterDirection.Output .Parameters("@RetVal").Direction = ParameterDirection.ReturnValue .Parameters("@CustomerID").Value = "ALFKI" .Parameters("@CompanyName").Direction = ParameterDirection.Output .Parameters("@ContactName").Direction = ParameterDirection.Output .ExecuteNonQuery() If Convert.ToInt32(.Parameters("@RetVal").Value) = 0 Then Console.WriteLine(.Parameters("@CompanyName").Value) Else Console.WriteLine("Customer not found") End If End With Visual C# .NET ... OleDbConnection cn = new OleDbConnection(strConn); cn.Open(); OleDbCommand cmd = cn.CreateCommand(); cmd.CommandText = "{? = CALL GetCustomer(?, ?, ?, ?)}"; cmd.Parameters.Add("@RetVal", OleDbType.Integer); cmd.Parameters.Add("@CustomerID", OleDbType.WChar, 5); cmd.Parameters.Add("@CompanyName", OleDbType.VarWChar, 40); cmd.Parameters.Add("@ContactName", OleDbType.VarWChar, 30); cmd.Parameters.Add("@ContactTitle", OleDbType.VarWChar, 30); cmd.Parameters["@ContactTitle"].Direction = ParameterDirection.Output; cmd.Parameters["@RetVal"].Direction = ParameterDirection.ReturnValue; cmd.Parameters["@CustomerID"].Value = "ALFKI"; cmd.Parameters["@CompanyName"].Direction = ParameterDirection.Output; cmd.Parameters["@ContactName"].Direction = ParameterDirection.Output; cmd.ExecuteNonQuery(); if (Convert.ToInt32(cmd.Parameters["@RetVal"].Value) == 0) Console.WriteLine(cmd.Parameters["@CompanyName"].Value); else Console.WriteLine("Customer not found"); --------------------
Чем больше узнаешь, тем больше не знаешь, но до истины всегда можно добраться. |
|||
|
||||
![]() ![]() ![]() |
Правила форума VB .NET | |
|
Если Вам помогли и атмосфера форума Вам понравилась, то заходите к нам чаще! С уважением, diadiavova. |
1 Пользователей читают эту тему (1 Гостей и 0 Скрытых Пользователей) | |
0 Пользователей: | |
« Предыдущая тема | VB .NET | Следующая тема » |
|
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности Powered by Invision Power Board(R) 1.3 © 2003 IPS, Inc. |