Calling An SQL Server 2005 Stored Procedure Within Microsoft Access And Reading Values

Jan 14, 2008

Goodday.

I have finally been able to create a connection from Access to the SQL 2005 Server and was able to call a stored proc (in Server) in the following way





Code Block
Dim cnn As New ADODB.Connection
Dim cmd As New ADODB.Command
Dim rst As New ADODB.Recordset

cnn.ConnectionString = "Provider='sqloledb'; Data Source='Private';" & _
"Initial Catalog='DBName';Integrated Security='SSPI';"

cnn.Open

cmd.ActiveConnection = cnn
cmd.CommandText = "sp_DefaultEntityData"
cmd.CommandType = adCmdStoredProc

Set rst = cmd.Execute


rst.MoveFirst
Do While Not rst.EOF
lstEntity.AddItem (rst.Fields(0)), 0
'lstEntity.AddItem (rst.Fields(1)), 1
rst.MoveNext
Loop






The Stored Proc is as follow:




Code Block
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

ALTER PROCEDURE [dbo].[sp_DefaultEntityData]
AS
BEGIN

SET NOCOUNT ON;

SELECT tblEntities.[Name], tblEntities.PrimaryKey
FROM tblEntities
ORDER BY tblEntities.PrimaryKey;

END






The table contains 24 entries

As you can see in the VB code, I am trying to read the returned "table" into an Access ListBox. The listbox should display the entities Name but not the Primary key, but the primary key should still be "stored" in the to so that it can be used to access other data.

I have moved the tables from Access to SQL Server 2005, and would also like to port all the sql queries to sp's in SQL Server. The old way for populating the listbox was a direct SQL query in the RowSource property field. I have tried to set the lstEntity.RowSource = rst but it did not work.

Here are my Q's:
1) As what does the SP return when it is called and is there a better way to catch it than I am doing at the moment?
2) How do I read the values into the listbox, without displaying the primary key in die box?

Thank you in advance!
Any help is very much appreciated.

View 2 Replies


ADVERTISEMENT

Reading Values Returned From A Stored Procedure

Nov 10, 2000

I am trying to use a stored procedure inside the scripter in a site server pipeline. Can anyone tell me how the scripter will read the the result which is a variable. The stored procedure is returning the right value when run in query analyzer but I don't know how to retrieve it inside the pipeline.

Thank you
JG

View 1 Replies View Related

Calling A .NET Dll From A SQL Server 2005 Stored Procedure

Sep 13, 2006

Setup:  I have a C# 2.0 class library that contains certain business logic that is to be triggered by certain database states.  There is a trigger that calls a stored procedure that is working properly (i.e. the stored procedure is being executed). Problem:  I have not yet figured out how to call the dll from the stored procedure.  Does anybody have any tutorials they could point me to or any advice to point me in the right direction? Thanks in advance for any help. 

View 2 Replies View Related

How To Pass Values To A Calling Stored Procedure

Nov 17, 2006

Currently i am working in a project of report generation in MS ACCESS.

The tables are in sql server 2000.
I have to write stored proc in ms access.

Illustration:
I am having a stored proc as follows

name: myproc
-------------------
Create procedure my_proc
@f1 char(1),
@f2 char(5)
As
select * from table1 where field1=@f1 and field2=@f2
________________________________________________
and calling proc
name: call_myproc

execute my_proc 'A','2004'

If i am getting the vales of field1/@f1 and field2/@f2 from forms in ms access.

I have to get the values from forms in ms access.

I have to write the calling proc as follows

my_proc [forms]![form_a].[Combo4],[forms]![form_a].[text12]

But ms access throws syntax error.

How is it possible to pass values from ms access FORMS to a calling stored procedure.

I have followed the way of creating and executing the stored procedure as given in the article as follows.
http://www.databasejournal.com/features/msaccess/article.php/10895_3363511_1

As per the given link. They did not give values dynamically.

could you please help me to fix this problem ?

regards,
Krishna

View 1 Replies View Related

Calling A Stored Procedure From ADO.NET 2.0-VB 2005 Express: Working With SELECT Statements In The Stored Procedure-4 Errors?

Mar 3, 2008

Hi all,

I have 2 sets of sql code in my SQL Server Management Stidio Express (SSMSE):

(1) /////--spTopSixAnalytes.sql--///

USE ssmsExpressDB

GO

CREATE Procedure [dbo].[spTopSixAnalytes]

AS

SET ROWCOUNT 6

SELECT Labtests.Result AS TopSixAnalytes, LabTests.Unit, LabTests.AnalyteName

FROM LabTests

ORDER BY LabTests.Result DESC

GO


(2) /////--spTopSixAnalytesEXEC.sql--//////////////


USE ssmsExpressDB

GO
EXEC spTopSixAnalytes
GO

I executed them and got the following results in SSMSE:
TopSixAnalytes Unit AnalyteName
1 222.10 ug/Kg Acetone
2 220.30 ug/Kg Acetone
3 211.90 ug/Kg Acetone
4 140.30 ug/L Acetone
5 120.70 ug/L Acetone
6 90.70 ug/L Acetone
/////////////////////////////////////////////////////////////////////////////////////////////
Now, I try to use this Stored Procedure in my ADO.NET-VB 2005 Express programming:
//////////////////--spTopSixAnalytes.vb--///////////

Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim sqlConnection As SqlConnection = New SqlConnection("Data Source = .SQLEXPRESS; Integrated Security = SSPI; Initial Catalog = ssmsExpressDB;")

Dim sqlDataAdapter As SqlDataAdapter = New SqlDataAdaptor("[spTopSixAnalytes]", sqlConnection)

sqlDataAdapter.SelectCommand.Command.Type = CommandType.StoredProcedure

'Pass the name of the DataSet through the overloaded contructor

'of the DataSet class.

Dim dataSet As DataSet ("ssmsExpressDB")

sqlConnection.Open()

sqlDataAdapter.Fill(DataSet)

sqlConnection.Close()

End Sub

End Class
///////////////////////////////////////////////////////////////////////////////////////////

I executed the above code and I got the following 4 errors:
Error #1: Type 'SqlConnection' is not defined (in Form1.vb)
Error #2: Type 'SqlDataAdapter' is not defined (in Form1.vb)
Error #3: Array bounds cannot appear in type specifiers (in Form1.vb)
Error #4: 'DataSet' is not a type and cannot be used as an expression (in Form1)

Please help and advise.

Thanks in advance,
Scott Chang

More Information for you to know:
I have the "ssmsExpressDB" database in the Database Expolorer of VB 2005 Express. But I do not know how to get the SqlConnection and the SqlDataAdapter into the Form1. I do not know how to get the Fill Method implemented properly.
I try to learn "Working with SELECT Statement in a Stored Procedure" for printing the 6 rows that are selected - they are not parameterized.




View 11 Replies View Related

Calling Stored Procedure From ACCESS

Jul 27, 2001

Can someone tell me how to call a stored procedure from Access?

Thanks,
Dianne

View 1 Replies View Related

JDBC: Calling A Stored Procedure With Multiple Return Values.

Jul 23, 2005

Using JDBC, is there a way to call a stored procedure with multiplereturn values? Thanks.

View 4 Replies View Related

Problems Calling SQL Express Stored Procedure From Access (using VBA)

Oct 4, 2007

Crossposted from VBA forum:

I'm upsizing a database from Access 2003 to a SQL Express backend combined with an Access frontend. Along the way, I'm trying to shift the larger queries into stored procedures, but many of our queries require variables. I'm having a hard time with the VBA to run this stored procedure, and looking for suggestions that make sense to a relative newbie to VBA.

Here's my code, which is being triggered by a button click on a form containing input boxes StartDt and EndDt for the date range:




Code Block

Private Sub btnDateFormQuery_Click()
'On Error GoTo Err_btnDateFormQuery_Click

If CreateDSNConnection("server", "database", "user", "password") Then
'// All is okay.
Else
'// Not okay.
End If

Dim rs_sp As Recordset 'Set in Global Module
Dim qdf As QueryDef 'Set in Global Module
Dim SP_SQL As String 'Set in Global Module
Dim Db As Database
Set Db = CurrentDb()
Set qdf = Db.CreateQueryDef("qry_Donors") 'Set in Global Module
qdf.ReturnsRecords = True 'Set in Global Module
qdf.ODBCTimeout = 15 'Set in Global Module
SP_SQL = "Execute sp_DonorQRY " & "'" & StartDt & "'" & ", " & "'" & EndDt & "'"
qdf.SQL = SP_SQL 'Set in Global Module

'Check Dates for errors
Call CheckDates 'Procedure to check dates
If CheckDatesErr = True Then
Exit Sub ' don't continue
End If

'Here is where we need to enter the code that will drive the query.


Set rs_sp = qdf.OpenRecordset
qdf.Close

rs_sp.MoveFirst

rs_sp.Close


Exit_btnDateFormQuery_Click:
Exit Sub

Err_btnDateFormQuery_Click:
MsgBox Err.Description
Resume Exit_btnDateFormQuery_Click

End Sub

During Debugging, when I reach the line "qdf.SQL = SP_SQL", I receive the following error:
Runtime Error '3129'Invalid SQL Statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'.


I've been able to copy out the value of SP_SQL and paste it into a pass-through query, and it runs beautifully. Just not having any luck trying to script it.

Thanks in advance.

View 1 Replies View Related

Connect To Microsoft Access Via Stored Procedure

Sep 29, 2006

Hi,

I'm new to SQL server, still in the beginning stage of learning SQL Server. I'm here would like know, besides using the Connectivity from the DTS Designer to connect to different databases, is it possible to connect the database, i.e: Access via stored procedure? and how? Pls advise...

I'm have been trying to look for the solution via a lot of SQL Server site, but fail to get what I want.

What I'm trying to do is something like :
First connect to the Database and Query the data, after that insert it into another database....

View 3 Replies View Related

Calling SQL 2005 Stored Procedure That Returns A Value

Apr 14, 2007

I have a stored procedure on a SQL server, which is workign correctly to check some date/time parameters and then insert a row into a log table.
I am calling it from an ASP page.   Initially I just called it and didn't worry about the return value.  However the Stored procedure now will return a value to determine if it made the change or not and if not why (ie log entry was at incorrect time etc).
 I woudl liek to capture this returned value in my code to display a message to the user but am havign problems finding the right way to get the value.
I am calling the SP as follows:
     Shared Sub createlogentry(ByVal ID, ByVal tme, ByVal val)        Dim result As String        Dim cs As String = ConfigurationManager.ConnectionStrings("connecttion1").ToString        Using con As New System.Data.SqlClient.SqlConnection(cs)            con.Open()            Dim cmd As New System.Data.SqlClient.SqlCommand()            cmd.Connection = con            cmd.CommandType = Data.CommandType.StoredProcedure            cmd.CommandText = "CreateLogEntry"            cmd.Parameters.Add("@ChID", Data.SqlDbType.Int)            cmd.Parameters("@ChID").Value = ID            cmd.Parameters.Add("@Value", Data.SqlDbType.Int)            cmd.Parameters("@Value").Value = val            result = cmd.ExecuteNonQuery().ToString        End Using    End Sub
 
I have tried amending the ExecuteNonQuery line to ExecuteReader()
 Any help appreciated
Regards
Clive

View 3 Replies View Related

Calling Web Service In Stored Procedure (SQL 2005)

Aug 18, 2006

I need to create a stored procedure (SQL 2005). I did it in C# (Visual Studio). The .dll file (inside) uses web services of Project Server 2007 (I just need to log on, create a project and log out). I prepared 2 files (exactly the same code): dll an exe. the .exe works fine. the problem is with .dll file (stored procedure in SQL)...

by the way: I created serialization file with sgen tool.

the problems start when I am trying to register these 2 .dlls in SQL server. I can do that in unsafe mode only. when I am trying to register them in externall access (normal dll) and safe mode (serialization .dll) I am getting errors:

CREATE ASSEMBLY failed because method "add_QueueCheckInProjectCompleted" on type "ConsoleApplication11.ProjectWebSvc.Project" in external_access assembly "ConsoleApplication11" has a synchronized attribute. Explicit synchronization is not allowed in external_access assemblies

thus I did it in unsafe mode (both of them). than I created the procedure.

Now, I tried to call that procedure. I am getting error:

A .NET Framework error occurred during execution of user defined routine or aggregate 'Main':

System.Net.WebException: The request failed with the error message:

--

<html><head><title>Object moved</title></head><body>

<h2>Object moved to <a href="http://my_comp:22278/projectserver/_layouts/1033/error.aspx?ErrorText=Object%20reference%20not%20set%20to%20an%20instance%20of%20an%20object%2E">here</a>.</h2>

</body></html>

--.

System.Net.WebException:

at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)

at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)

at ConsoleApplication11.ProjectWebSvc.Project.QueueCreateProject(Guid jobUid, ProjectDataSet dataset, Boolean validateOnly)

at ConsoleApplication11.Program.Main()

That means "Object reference not set to an instance of an object". the problem occurs when calling QueueCreateProject method

I dont understand that error. I wrote the same code for .dll and .exe. the .exe file is working ok (no errors) but .dll (as a stored procedure) shows this error



my code in C#:

using System;

using System.Collections.Generic;

using System.Text;

using System.Data.SqlClient;

using System.Net;

using PSLibrary = Microsoft.Office.Project.Server.Library;

namespace ConsoleApplication11

{

public class Program

{

public static void Main()

{

const string LOGINWINDOWS = "_vti_bin/PSI/LoginWindows.asmx";

string baseUrl = "http://localhost:22278/projectserver/";

CookieContainer cookies = new CookieContainer();



LoginWindowsWebSvc.LoginWindows loginWindows = new LoginWindowsWebSvc.LoginWindows();

loginWindows.Url = baseUrl + LOGINWINDOWS;

loginWindows.Credentials = CredentialCache.DefaultCredentials;

loginWindows.Login();

ProjectWebSvc.Project project = new ProjectWebSvc.Project();

project.Credentials = loginWindows.Credentials;

project.Url = baseUrl + "_vti_bin/psi/project.asmx";

ProjectWebSvc.ProjectDataSet dsProject = new ProjectWebSvc.ProjectDataSet();

ProjectWebSvc.ProjectDataSet.ProjectRow projectRow = dsProject.Project.NewProjectRow();

Guid projectGuid = Guid.NewGuid();

projectRow.PROJ_UID = projectGuid;

projectRow.PROJ_TYPE = 0;

projectRow.PROJ_NAME = "Jakis";

projectRow.PROJ_SESSION_UID = Guid.NewGuid();

dsProject.Project.AddProjectRow(projectRow);

Guid jobGuid = Guid.NewGuid();

project.QueueCreateProject(jobGuid, dsProject, false);

System.Threading.Thread.Sleep(5000);



loginWindows.Logoff();

project.Credentials = null;

}

}

}





any help will be appreciated. my email is: stro.na@interia.pl

View 4 Replies View Related

ADO - Cannot Access The Return Parameter Of A Stored Procedure On SQL Server 2005

Apr 18, 2007

Hello,



I am trying to access the Return Value provided by a stored procedure executed on SQL Server 2005. The stored procedure has already been tested and it returns the required value. However, I do not know how to access this value. I have tried appending a parameter to the command object using "adParamReturnValue" but that only returns an error. The code works fine without appending this parameter. I have tested it by grabbing the recordset and returning the first field.



To avoid any confusion, I'm not talking about adding an "output" parameter to the stored procedure. I just want to be able to access the return value provided when the procedure is executed. Below is some of the code I am using.



try{

pCmd.CreateInstance((__uuidof(Command)));

pCmd->ActiveConnection = m_pConnection;

pCmd->CommandType = adCmdStoredProc;

pCmd->CommandText = _bstr_t("dbo.GetFlightPlan");



............................ code here ........................................



pCmd->Parameters->Append(pCmd->CreateParameter(_bstr_t("AircraftID"),adChar,adParamInput,7,vAcId));

pCmd->Parameters->Append(pCmd->CreateParameter(_bstr_t("DepartureAerodome"),adChar,adParamInput,4,vDepAero));

pCmd->Parameters->Append(pCmd->CreateParameter(_bstr_t("DestinationAerodome"),adChar,adParamInput,4,vDestAero));

pCmd->Parameters->Append(pCmd->CreateParameter(_bstr_t("DepartureHour"),adInteger,adParamInput,2,vDepHour));

pCmd->Parameters->Append(pCmd->CreateParameter(_bstr_t("DepartureMin"),adInteger,adParamInput,2,vDepMin));



VARIANT returnVal;

returnVal.vt = VT_I2;

returnVal.intVal = NULL;

pCmd->Parameters->Append(pCmd->CreateParameter(_bstr_t("RETURNVALUE"),adInteger,adParamReturnValue,sizeof(_variant_t),returnVal));

//Get Return value by executing the command

//The return value should be the DB unique ID.



pCmd->Execute(NULL, NULL, adCmdStoredProc);

int uniqueId = returnVal.intVal;

//pRst = pCmd->Execute(NULL, NULL, adCmdStoredProc);

//GetFieldValue(0,pRst,uniqueId);



printf("The DB unique ID is: %i",uniqueId);

return uniqueId;

}



Cheers,

Seth

View 1 Replies View Related

Microsoft KB 308049: How To Call A Parameterized Stored Procedure By Using ADO.NET 2.0-VB 2005 Express-pubs Is Processed By ?

Mar 10, 2008

Hi all,

I tried to use the "How to call a Parameterterized Stored Procedure by Using ADO.NET and Visual Basic.NET" in http://support.microsoft.com/kb/308049 to learn "Use DataReader to Return Rows and Parameter" in my VB 2005 Express. I did the following things:

1) created a stored procedure "pubsTestProc1.sql" in my SQL Server Management Studio Express (SSMSE):


USE pubs

GO

Create Procedure TestProcedure

(

@au_idIN varchar (11),

@numTitlesOUT Integer OUTPUT

)

As

select A.au_fname, A.au_lname, T.title

from authors as A join titleauthor as TA on

A.au_id=TA.au_id

join titles as T

on T.title_id=TA.title_id

where A.au_id=@au_idIN

set @numTitlesOUT = @@Rowcount

return (5)

2) created a project "pubsTestProc1.vb" in my VB 2005 Express and copied the following code from http://support.microsoft.com/kb/308049 (i.e. Added the code to the Form_Load eventQL_Client) :


Imports System.Data

Imports System.Data.Client

Imports System.Data.SqlType

Imports System.Data.Odbc

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)

RetValue.Direction = ParameterDirection.ReturnValue

Dim auIDIN As SqlParameter = testCMD.Parameters.Add & _

("@au_idIN", SqlDbType.VarChar, 11)

auIDIN.Direction = ParameterDirection.Input

Dim NumTitles As SqlParameter = testCMD.Parameters.Add & _

("@numtitlesout", SqlDbType.Int)

NumTitles.Direction = ParameterDirection.Output

auIDIN.Value = "213-46-8915"

PubsConn.Open()

Dim myReader As SqlDataReader = testCMD.ExecuteReader()

Console.WriteLine("Book Titles for this Author:")

Do While myReader.Read

Console.WriteLine("{0}", myReader.GetString(2))

Loop

myReader.Close()

Console.WriteLine("Return Value: " & (RetValue.Value))

Console.WriteLine("Number of Records: " & (NumTitles.Value))

End Sub

End Class
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
I compiled the above code and I got the following 15 errors:
Warning 1 Namespace or type specified in the Imports 'System.Data.Client' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases. C:Documents and Settingse1enxshcMy DocumentsVisual Studio 2005ProjectspubsTestProc1pubsTestProc1Form1.vb 2 9 pubsTestProc1
Warning 2 Namespace or type specified in the Imports 'System.Data.SqlType' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases. C:Documents and Settingse1enxshcMy DocumentsVisual Studio 2005ProjectspubsTestProc1pubsTestProc1Form1.vb 3 9 pubsTestProc1
Error 3 Type 'SqlConnection' is not defined. C:Documents and Settingse1enxshcMy DocumentsVisual Studio 2005ProjectspubsTestProc1pubsTestProc1Form1.vb 10 25 pubsTestProc1
Error 4 ')' expected. C:Documents and Settingse1enxshcMy DocumentsVisual Studio 2005ProjectspubsTestProc1pubsTestProc1Form1.vb 15 30 pubsTestProc1
Error 5 Name 'testCMD' is not declared. C:Documents and Settingse1enxshcMy DocumentsVisual Studio 2005ProjectspubsTestProc1pubsTestProc1Form1.vb 17 9 pubsTestProc1
Error 6 ')' expected. C:Documents and Settingse1enxshcMy DocumentsVisual Studio 2005ProjectspubsTestProc1pubsTestProc1Form1.vb 20 23 pubsTestProc1
Error 7 Name 'RetValue' is not declared. C:Documents and Settingse1enxshcMy DocumentsVisual Studio 2005ProjectspubsTestProc1pubsTestProc1Form1.vb 21 9 pubsTestProc1
Error 8 ')' expected. C:Documents and Settingse1enxshcMy DocumentsVisual Studio 2005ProjectspubsTestProc1pubsTestProc1Form1.vb 23 23 pubsTestProc1
Error 9 Name 'auIDIN' is not declared. C:Documents and Settingse1enxshcMy DocumentsVisual Studio 2005ProjectspubsTestProc1pubsTestProc1Form1.vb 24 9 pubsTestProc1
Error 10 ')' expected. C:Documents and Settingse1enxshcMy DocumentsVisual Studio 2005ProjectspubsTestProc1pubsTestProc1Form1.vb 26 28 pubsTestProc1
Error 11 Name 'NumTitles' is not declared. C:Documents and Settingse1enxshcMy DocumentsVisual Studio 2005ProjectspubsTestProc1pubsTestProc1Form1.vb 27 9 pubsTestProc1
Error 12 Name 'auIDIN' is not declared. C:Documents and Settingse1enxshcMy DocumentsVisual Studio 2005ProjectspubsTestProc1pubsTestProc1Form1.vb 29 9 pubsTestProc1
Error 13 Type 'SqlDataReader' is not defined. C:Documents and Settingse1enxshcMy DocumentsVisual Studio 2005ProjectspubsTestProc1pubsTestProc1Form1.vb 32 25 pubsTestProc1
Error 14 Name 'RetValue' is not declared. C:Documents and Settingse1enxshcMy DocumentsVisual Studio 2005ProjectspubsTestProc1pubsTestProc1Form1.vb 39 47 pubsTestProc1
Error 15 Name 'NumTitles' is not declared. C:Documents and Settingse1enxshcMy DocumentsVisual Studio 2005ProjectspubsTestProc1pubsTestProc1Form1.vb 40 52 pubsTestProc1
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
First, I am completely lost here alreay. Second, I should have the following code from http://support.microsoft.com/kb/308049 too:

OLE DB Data Provider

Dim PubsConn As OleDbConnection = New OleDbConnection & _

("Provider=sqloledb;Data Source=server;" & _

"integrated security=sspi;initial Catalog=pubs;")

Dim testCMD As OleDbCommand = New OleDbCommand & _

("TestProcedure", PubsConn)

testCMD.CommandType = CommandType.StoredProcedure

Dim RetValue As OleDbParameter = testCMD.Parameters.Add & _

("RetValue", OleDbType.Integer)

RetValue.Direction = ParameterDirection.ReturnValue

Dim auIDIN As OleDbParameter = testCMD.Parameters.Add & _

("@au_idIN", OleDbType.VarChar, 11)

auIDIN.Direction = ParameterDirection.Input

Dim NumTitles As OleDbParameter = testCMD.Parameters.Add & _

("@numtitlesout", OleDbType.Integer)

NumTitles.Direction = ParameterDirection.Output

auIDIN.Value = "213-46-8915"

PubsConn.Open()

Dim myReader As OleDbDataReader = testCMD.ExecuteReader()

Console.WriteLine("Book Titles for this Author:")

Do While myReader.Read

Console.WriteLine("{0}", myReader.GetString(2))

Loop

myReader.Close()

Console.WriteLine("Return Value: " & (RetValue.Value))

Console.WriteLine("Number of Records: " & (NumTitles.Value))
//////////////////////////////////////////////////////////////////////////////////////////////////////
Now, I am completely out of touch with these two sets of the code from the Microsoft KB 308049 and do not know how to proceed to get the following output stated in the Microsoft KB 308049-see the below:




4.
Modify the connection string for the Connection object to point to the server that is running SQL Server.

5.


Run the code. Notice that the ExecuteScalar method of the Command object returns the parameters. ExecuteScalar also returns the value of column 1, row 1 of the returned rowset. Thus, the value of intCount is the result of the count function from the stored procedure.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Please help and tell me what I should do to get this project landed on the right track.

Thanks in advance,
Scott Chang



View 16 Replies View Related

Microsoft Access To SQL Server 2005

Mar 6, 2006

Hi,

I have a database in MSACCESS 2003 that is 680MB (after compacting) and contains 41 tables.

I tried to import these tables to SQL Server 2005 (express edition) using the :"upsizing wizard" provided in MSACCESS. The wizard works fine but all the tables are not being imported to SQL Server (only 19 tables are getting imported) and the size of the database in SQL Server (the ".mdf file") is 1.03 GB (I have tried using the "shrink" option also) . Further, when I try to open one of the tables (which has 625295 rows and 90 columns) , it takes lot of time to display all records.

So, my problem is do I need to set any options for any of these above issues, I tried to look for any information regarding this but was unsuccessful.

Any help on this will be very much helpful for me!

thanks

View 3 Replies View Related

Calling A Stored Procedure Inside Another Stored Procedure (or Nested Stored Procedures)

Nov 1, 2007

Hi all - I'm trying to optimized my stored procedures to be a bit easier to maintain, and am sure this is possible, not am very unclear on the syntax to doing this correctly.  For example, I have a simple stored procedure that takes a string as a parameter, and returns its resolved index that corresponds to a record in my database. ie
exec dbo.DeriveStatusID 'Created'
returns an int value as 1
(performed by "SELECT statusID FROM statusList WHERE statusName= 'Created') 
but I also have a second stored procedure that needs to make reference to this procedure first, in order to resolve an id - ie:
exec dbo.AddProduct_Insert 'widget1'
which currently performs:SET @statusID = (SELECT statusID FROM statusList WHERE statusName='Created')INSERT INTO Products (productname, statusID) VALUES (''widget1', @statusID)
I want to simply the insert to perform (in one sproc):
SET @statusID = EXEC deriveStatusID ('Created')INSERT INTO Products (productname, statusID) VALUES (''widget1', @statusID)
This works fine if I call this stored procedure in code first, then pass it to the second stored procedure, but NOT if it is reference in the second stored procedure directly (I end up with an empty value for @statusID in this example).
My actual "Insert" stored procedures are far more complicated, but I am working towards lightening the business logic in my application ( it shouldn't have to pre-vet the data prior to executing a valid insert). 
Hopefully this makes some sense - it doesn't seem right to me that this is impossible, and am fairly sure I'm just missing some simple syntax - can anyone assist?
 

View 1 Replies View Related

SQL Server 2012 :: Can't Get Row Count To Return To Calling Stored Procedure

Jul 9, 2014

SQL Server 2012 Standard SP 1.

Stored procedure A calls another stored procedure B. Rowcount is set properly in called procedure B, but does not seem to return it to calling procedure A. Otherwise the two stored procedures are working correctly. Here is the relevant code from the calling procedure A:

declare @NumBufferManagerRows int = 0;
exec persist.LoadBufferManager @StartTicks, @EndTicks, @TimeDiff, @NumBufferManagerRows;
print 'BufferManagerRows';
print @NumBufferManagerRows;

Print statement prints @NumBufferManagerRows as 0.

Here is the called stored procedure B:

CREATE PROCEDURE [persist].[LoadBufferManager]
-- Add the parameters for the stored procedure here
@StartTicks bigint,
@EndTicks bigint,
@TimeDiff decimal(9,2),
@NumRows int OUTPUT

[Code] ...

View 2 Replies View Related

SQL Server 2008 :: Calling Stored Procedure Into Report Builder

Oct 23, 2015

I am trying to call a stored procedure into report builder. The stored procedure has 2 parameters. When I run the report with allowing nulls and blank value in the parameters it works fine, but when I enter a value in a parameter it ignores the where clause I had in the original query(stored procedure) and displays everything.

View 3 Replies View Related

Connecting SQL Server Express 2005 To A Microsoft Access 97 Database

Nov 3, 2006

I want to use SQL Server to query an Access Database with about 40,000 rows of data. If possible, I don't want to upsize the database because others need acess to it in the ACC97 format. Is there a way to use ODBC to connect to the ACC97 database so that I can use the SQL query capability of SQL server to query the database.

I know access allows you to write some SQL queries but I need the power of the SQL server and now it is a matter of curiosity because I've been searching for this answer for about 8 hours.

View 1 Replies View Related

Configuring A Linked Microsoft Access Database On SQL Server 2005

Nov 7, 2007

The following installation:

- Microsoft SQL Server 2005 Standard Edition running on Microsoft Windows Server 2003 Standard Edition
- Client Service for Netware installed.
- Access 2000 database in a Novell Directory Services (NDS) Environment
- SQL Server service running under local Administrator account.


Linked server configured as follow:

Linked server: MyDB
Provider: Microsoft Jet 4.0 OLE DB Provider
Product name: Access 2000
Data Source: UNC path to my Access database

Security: Admin with no password (default Access behaviour)

I can connect to my access database by following the next steps:

- Open Management studio on the SQL Server itself (where I'm logged in as Administrator)
- Connect using Windows Authentication (Administrator)
- Create a new query, run EXEC sp_tables_ex 'MyDB'

This will return all the tables from the Access database.

I can also make a view pointing to MyDB...MyTable.

Enough prove to me It can work....

So far so good


But now the tricky part.

When I login as 'sa', I can't connect and will receive the following message:

OLE DB provider "Microsoft.Jet.OLEDB.4.0" for linked server "MyDB" returned message "'Full UNC to my access database' is not a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides.".Msg 7303, Level 16, State 1, Procedure sp_tables_ex, Line 41Cannot initialize the data source object of OLE DB provider "Microsoft.Jet.OLEDB.4.0" for linked server "MyDB".


(In real life I want to connect to my SQL 2005 Server from a ASP.NET (2.0) application using SQL authentication, but as long as I can't get the above working this is not important for now)

View 3 Replies View Related

Is There A Way To Import Tables From Microsoft Access 2003 With SQL Server 2005 Express?

Apr 21, 2006

Hi,

I've just installed SQL Server 2005 Express Advanced and I haven't found a way to import Microsoft Access 2003 files. Is there a way to do it?

Thanks in advance,

Sergio Oliveira

View 1 Replies View Related

Help: Why Excute A Stored Procedure Need To More 30 Seconds, But Direct Excute The Query Of This Procedure In Microsoft SQL Server Management Studio Under 1 Second

May 23, 2007

Hello to all,
I have a stored procedure. If i give this command exce ShortestPath 3418, '4125', 5 in a script and excute it. It takes more 30 seconds time to be excuted.
but i excute it with the same parameters  direct in Microsoft SQL Server Management Studio , It takes only under 1 second time
I don't know why?
Maybe can somebody help me?
thanks in million
best Regards
Pinsha 
My Procedure Codes are here:set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[ShortestPath] (@IDMember int, @IDOther varchar(1000),@Level int, @Path varchar(100) = null output )
AS
BEGIN
 
if ( @Level = 1)
begin
select @Path = convert(varchar(100),IDMember)
from wtcomValidRelationships
where wtcomValidRelationships.[IDMember]= @IDMember
and PATINDEX('%'+@IDOther+'%',(select RelationshipIDs from wtcomValidRelationships where IDMember = @IDMember) ) > 0
end
if (@Level = 2)
begin
select top 1 @Path = convert(varchar(100),A.IDMember)+'-'+convert(varchar(100),B.IDMember)
from wtcomValidRelationships as A, wtcomValidRelationships as B
where A.IDMember = @IDMember and charindex(convert(varchar(100),B.IDMember),A.RelationshipIDS) > 0
and PATINDEX('%'+@IDOther+'%',B.RelationshipIDs) > 0
end
if (@Level = 3)
begin
select top 1 @Path = convert(varchar(100),A.IDMember)+ '-'+convert(varchar(100),B.IDMember)+'-'+convert(varchar(100),C.IDMember)
from wtcomValidRelationships as A, wtcomValidRelationships as B, wtcomValidRelationships as C
where A.IDMember = @IDMember and charindex(convert(varchar(100),B.IDMember),A.RelationshipIDS) > 0
and charindex(convert(varchar(100),C.IDMember),B.RelationshipIDs) > 0 and PATINDEX('%'+@IDOther+'%',C.RelationshipIDs) > 0
end
if ( @Level = 4)
begin
select top 1 @Path = convert(varchar(100),A.IDMember)+ '-'+convert(varchar(100),B.IDMember)+'-'+convert(varchar(100),C.IDMember)+'-'+convert(varchar(100),D.IDMember)
from wtcomValidRelationships as A, wtcomValidRelationships as B, wtcomValidRelationships as C, wtcomValidRelationships as D
where A.IDMember = @IDMember and charindex(convert(varchar(100),B.IDMember),A.RelationshipIDS) > 0
and charindex(convert(varchar(100),C.IDMember),B.RelationshipIDs) > 0 and charindex(convert(varchar(100),D.IDMember), C.RelationshipIDs) > 0
and PATINDEX('%'+@IDOther+'%',D.RelationshipIDs) > 0
end
if (@Level = 5)
begin
select top 1 @Path = convert(varchar(100),A.IDMember)+ '-'+convert(varchar(100),B.IDMember)+'-'+convert(varchar(100),C.IDMember)+'-'+convert(varchar(100),D.IDMember)+'-'+convert(varchar(100),E.IDMember)
from wtcomValidRelationships as A, wtcomValidRelationships as B, wtcomValidRelationships as C, wtcomValidRelationships as D, wtcomValidRelationships as E
where A.IDMember = @IDMember and charindex(convert(varchar(100),B.IDMember),A.RelationshipIDS) > 0
and charindex(convert(varchar(100),C.IDMember),B.RelationshipIDs) > 0 and charindex(convert(varchar(100),D.IDMember), C.RelationshipIDs) > 0
and charindex(convert(varchar(100),E.IDMember),D.RelationshipIDs) > 0 and PATINDEX('%'+@IDOther+'%',E.RelationshipIDs) > 0
end
if (@Level = 6)
begin
select top 1 @Path = '' from wtcomValidRelationships
end
END
 
 
 

View 6 Replies View Related

Learn To Access Stored Procedures With ADO.NET 2.0-VB 2005:How To Work With Output Parameters &&amp; Report Their Values In VB Forms?

Feb 11, 2008

Hi all,

In my SQL Server Management Studio Express (SSMSE), pubs Database has a Stored Procedure "byroyalty":

ALTER PROCEDURE byroyalty @percentage int

AS

select au_id from titleauthor

where titleauthor.royaltyper = @percentage

And Table "titleauthor" is:
au_id title_id au_ord royaltyper




172-32-1176
PS3333
1
100

213-46-8915
BU1032
2
40

213-46-8915
BU2075
1
100

238-95-7766
PC1035
1
100

267-41-2394
BU1111
2
40

267-41-2394
TC7777
2
30

274-80-9391
BU7832
1
100

409-56-7008
BU1032
1
60

427-17-2319
PC8888
1
50

472-27-2349
TC7777
3
30

486-29-1786
PC9999
1
100

486-29-1786
PS7777
1
100

648-92-1872
TC4203
1
100

672-71-3249
TC7777
1
40

712-45-1867
MC2222
1
100

722-51-5454
MC3021
1
75

724-80-9391
BU1111
1
60

724-80-9391
PS1372
2
25

756-30-7391
PS1372
1
75

807-91-6654
TC3218
1
100

846-92-7186
PC8888
2
50

899-46-2035
MC3021
2
25

899-46-2035
PS2091
2
50

998-72-3567
PS2091
1
50

998-72-3567
PS2106
1
100

NULL
NULL
NULL
NULL
////////////////////////////////////////////////////////////////////////////////////////////
I try to do an ADO.NET 2.0-VB 2005 programming in my VB 2005 Express to get @percentage printed out in the VB Form1. I read some articles in the websites and MSDN about this task and I am very confused about "How to Work with Output Parameters & Report their Values in VB Forms": (1) Do I need the Form.vb [Design] and specify its properties of the object and classes I want to printout? (2) After the SqlConnectionString and the connection.Open(), how can I bring the value of @percentage to the Form.vb? (3) The following is my imcomplete, crude draft code:

Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.SqlTypes

Public Class Form1

Dim connectionString As String = "Data Source=.SQLEXPRESS;Initial Catalog=pubs;Integrated Security=SSPI;"

Dim connection As SqlConnection = New

SqlConnection(connectionString)

Try

connection.Open()

Dim command As SqlCommand = New SqlCommand("byroyalty", connection)

command.CommandType = CommandType.StoredProcedure
...................................................................
..................................................................
etc.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
From the above-mentioned (1), (2) and (3), you can see how much I am lost/confused in attempting to do this task. Please help and give me some guidances and good key instructions for getting the output parameter printed out in the FORM.vb in my VB 2005 Express project.

Thanks in advance,
Scott Chang


View 11 Replies View Related

Reading Stored Procedure In Asp.net 2.0

Nov 30, 2007

Hi, I'm having a difficult time getting the result from a stored procedure, where the result is stored in a dataset, and then displayed in a gridview.  I have the following code:  //SqlConnection conn = new SqlConnection("Data Source=GTS-02;Initial Catalog=Victor;User ID=name;Password=.pass"); string conn = System.Configuration.ConfigurationManager.AppSettings.GetValues("ConnectionString")[0]; SqlConnection m_dbConn = null; SqlCommand sqlCmd = new SqlCommand(); DataSet dsTest = new DataSet();

m_dbConn = new SqlConnection(conn); sqlCmd.CommandType = CommandType.StoredProcedure; sqlCmd = new SqlCommand("TESTME", m_dbConn); SqlParameter parmParam1 = new SqlParameter("@Param1", TextBox2.Text); sqlCmd.Parameters.Add(parmParam1); m_dbConn.Open(); SqlDataAdapter sqlDataIn = new SqlDataAdapter(sqlCmd); sqlDataIn.Fill(dsTest, "Result");

GridView1.DataSource = dsTest.Tables["Result"]; GridView1.DataBind(); m_dbConn.Close();I can see through debugging that I'm connected to the sql database, but I'm not able to retrieve the result from the stored procedure.  Any advice would be greatly appreciated! DZ 

View 1 Replies View Related

Microsoft Access Doesn't Support Design Changes To The Version Of Microsoft SQL Server

Jul 23, 2005

Dear All,Access adp on sql-server 2000After upgrating to A2003 updating data with 1 perticular combobox causes theprogram to hangs without any error-msg.Traying to change te combobox recordsource i get this error:This version of Microsoft Access doesn't support design changes to theversion of Microsoft SQL Server your project is connected to. See theMicrosoft Office Update Web site for the latest information and downloads(on the Help menu, click Office on the Web). Your design changes will not besaved.The solution in :http://support.microsoft.com/defaul...kb;en-us;313298tolks about SP 'dt_verstamp007' but I have SP 'dt_verstamp006'What should I do.Is the failure of the combobox also caused by the absence of dt_verstamp007???Filip

View 2 Replies View Related

(Could Not Find Stored Procedure ''.) When Calling A User Defined Procedure

Feb 4, 2008

Hi,I'm tring to call a stored procedure i'v made from a DNN module, via .net control.When I try to execute this sql statement: EXEC my_proc_name 'prm_1', 'prm_2', ... the system displays this error: Could not find stored procedure ''. (including the trailings [".] chars :)I've tried to run the EXEC statement from SqlServerManagement Studio, and seems to works fine, but sometimes it displays the same error. So i've added the dbname and dbowner as prefix to my procedure name in the exec statement and then in SqlSrv ManStudio ALWAYS works, but in dnn it NEVER worked... Why? I think it could be a db permission problem but i'm not able to fix this trouble, since i'm not a db specialist and i don't know which contraint could give this problem. Also i've set to the ASPNET user the execute permissions for my procedure... nothing changes :( Shoud someone could help me? Note that I'm using a SqlDataSource object running the statement with the select() method (and by setting the appropriate SelectCommandType = SqlDataSourceCommandType.StoredProcedure ) and I'm using the 2005 sql server express Thank in advance,(/d    

View 3 Replies View Related

Reading Stored Procedure Output

Apr 17, 2007

Hi all,



I've been wrestling with something for quite some time, and can't seem to get anything figured out. I'd appeciate some guidance.



I have adopted a couple of different approaches, but have been unable to get any of them to yield the information I'm looking for. In essence, I want to use the output of a Reporting Service report for archiving in another database. I have attempted to use the Reporting Services web service to achieve this, but got absolutely nowhere.



Today, I have created a stored procedure which mimics the behaviour of my report and have tried to use SSIS to read the result set from this stored procedure via both a DataReader Source and an OLE DB source. The problem is that the SP takes 4 parameters, and for the life of me it seems impossible to get these parameters down to the SP in a way that SSIS can parse and generate the columns.



I've reached a dead end in terms of my own knowledge. Has anyone done anything like this before and could advise me on the best way to achieve it? Do my aims even make sense, or do I need to rethink the process of using this kind of data?



At this stage, any help would be very much appreciated. Many thanks...

View 10 Replies View Related

Calling Stored Procedures In MS Access

Nov 3, 2000

can anyone tell me how to call SQL stored procedures in MS Access97...
appreciate any help

View 4 Replies View Related

How To Access Analysis Service 2005 Cubes Through Normal Stored Procedure

Apr 2, 2007



Hi,



Can anybody tell me How to access Analysis Service 2005 cubes through normal Stored Procedure.



Basically can write a stored procedure that we normally write in database service and use it access the Analysis Service 2005 cubes.



Is it possible



Regards,

gokul

View 1 Replies View Related

Reading An OUTPUT Parameter From A Stored Procedure Into A Variable

Oct 2, 2007

Hello,
I am struggling with this, having read many msdn articles and posts I am non the wiser. I have a sproc with an output parameter @regemail. I can call the sproc OK from my code as below, via a tableadapter. And the sproc works as desired from management studio express. I want to get the result returned in the OUTPUT parameter (NOT the Return Value) and place it in a variable. Can anyone advise how I can do this? J.
THE CODE I USE TO CALL THE SPROC
Dim tableAdapter As New DataSet1TableAdapters.RegistrationTableAdaptertableAdapter.SPVerifyUser(strRegGuid, String.Empty)
 THE STORED PROCEDURECREATE Proc [prs_VerifyUser
 @regid uniqueidentifier,@regemail nvarchar(250) OUTPUT
ASBEGIN
IF EXISTS(SELECT RegEmail from dbo.Registration WHERE RegID = @regid)
BEGIN
SELECT @regemail = RegEmail FROM Registration WHERE RegID = @regid
Return 1
END
Return 2
END

View 4 Replies View Related

Calling Stored Procedure Fromanother Stored Procedure

Oct 10, 2006

Hi,I am getting error when I try to call a stored procedure from another. I would appreciate if someone could give some example.My first Stored Procedure has the following input output parameters:ALTER PROCEDURE dbo.FixedCharges @InvoiceNo int,@InvoiceDate smalldatetime,@TotalOut decimal(8,2) outputAS .... I have tried using the following statement to call it from another stored procedure within the same SQLExpress database. It is giving me error near CALL.CALL FixedCharges (@InvoiceNo,@InvoiceDate,@TotalOut )Many thanks in advanceJames

View 16 Replies View Related

Calling A Stored Procedure Or Function From Another Stored Procedure

Mar 2, 2007

Hello people,

When I am trying to call a function I made from a stored procedure of my creation as well I am getting:

Running [dbo].[DeleteSetByTime].

Cannot find either column "dbo" or the user-defined function or aggregate "dbo.TTLValue", or the name is ambiguous.

No rows affected.

(0 row(s) returned)

@RETURN_VALUE =

Finished running [dbo].[DeleteSetByTime].

This is my function:

ALTER FUNCTION dbo.TTLValue

(

)

RETURNS TABLE

AS

RETURN SELECT Settings.TTL FROM Settings WHERE Enabled='true'

This is my stored procedure:

ALTER PROCEDURE dbo.DeleteSetByTime

AS

BEGIN



SET NOCOUNT ON



DECLARE @TTL int

SET @TTL = dbo.TTLValue()



DELETE FROM SetValues WHERE CreatedTime > dateadd(minute, @TTL, CreatedTime)

END

CreatedTime is a datetime column and TTL is an integer column.

I tried calling it by dbo.TTLValue(), dbo.MyDatabase.TTLValue(), [dbo].[MyDatabase].[TTLValue]() and TTLValue(). The last returned an error when saving it "'TTLValue' is not a recognized built-in function name". Can anybody tell me how to call this function from my stored procedure? Also, if anybody knows of a good book or site with tutorials on how to become a pro in T-SQL I will appreciate it.

Your help is much appreciated.

View 6 Replies View Related

Calling A Stored Procedure

Mar 23, 2007

Hi, i've had this query method:
34           public void AddDagVerslagCategorie(int logID, HistoriekDetail historiekDetail)35           {36               SqlConnection oConn = new SqlConnection(_connectionString);37               string strSql = "Insert into LogDetail (LogID, CategorieID, Inhoud)";38               strSql += "values(@logID, @categorieID, @inhoud)";39               SqlCommand oCmd = new SqlCommand(strSql, oConn);40               oCmd.Parameters.Add(new SqlParameter("@logID", SqlDbType.Int)).Value = logID;41               oCmd.Parameters.Add(new SqlParameter("@categorieID", SqlDbType.Int)).Value = historiekDetail.CategorieID;42               oCmd.Parameters.Add(new SqlParameter("@inhoud", SqlDbType.VarChar, 100)).Value = historiekDetail.Inhoud;43   44               try45               {46                   oConn.Open();47                   int rowsAffected = oCmd.ExecuteNonQuery();48                   if (rowsAffected == 0) throw new ApplicationException("Fout toevoegen historiek detail");49                   oCmd.CommandText = "select @@IDENTITY";50                   oCmd.Parameters.Clear();51                   historiekDetail.HistoriekDetailID = (int)(decimal)oCmd.ExecuteScalar();52               }53               catch (Exception ex)54               {55                   throw new ApplicationException("Fout toevoegen historiek detail: " + ex.Message);56               }57               finally58               {59                   if (oConn.State == ConnectionState.Open) oConn.Close();60               }61           }
which i've converted to a stored procedure: 1 ALTER PROCEDURE [dbo].[insert_DagVerslagDetail]
2 -- Add the parameters for the stored procedure here
3 @dagverslagdetailID int,
4 @logID int,
5 @categorieID int,
6 @inhoud varchar(100)
7 AS
8 BEGIN
9 -- SET NOCOUNT ON added to prevent extra result sets from
10 -- interfering with SELECT statements.
11 SET NOCOUNT ON;
12 SET @dagverslagdetailID = SCOPE_IDENTITY()
13
14 -- Insert statements for procedure here
15 BEGIN TRANSACTION
16 INSERT LogDetail (LogID, CategorieID, Inhoud)
17 VALUES(@logID, @categorieID, @inhoud)
18 COMMIT TRANSACTION
19 END
  
 
Now i would like to call that stored procedure in my previous method, so i've changed it to this:
 1 public void AddDagVerslagCategorie(int logID, HistoriekDetail historiekDetail)
2 {
3 SqlConnection oConn = new SqlConnection(_connectionString);
4 string strSql = "insert_DagVerslagDetail";
5 strSql += "values(@logID, @categorieID, @inhoud)";
6 SqlCommand oCmd = new SqlCommand(strSql, oConn);
7 oCmd.CommandType = CommandType.StoredProcedure;
8 oCmd.Parameters.Add(new SqlParameter("@logID", SqlDbType.Int)).Value = logID;
9 oCmd.Parameters.Add(new SqlParameter("@categorieID", SqlDbType.Int)).Value = historiekDetail.CategorieID;
10 oCmd.Parameters.Add(new SqlParameter("@inhoud", SqlDbType.VarChar, 100)).Value = historiekDetail.Inhoud;
11
12 try
13 {
14 oConn.Open();
15 int rowsAffected = oCmd.ExecuteNonQuery();
16 if (rowsAffected == 0) throw new ApplicationException("Fout toevoegen historiek detail");
17 oCmd.CommandText = "select @@IDENTITY";
18 oCmd.Parameters.Clear();
19 historiekDetail.HistoriekDetailID = (int)(decimal)oCmd.ExecuteScalar();
20 }
21 catch (Exception ex)
22 {
23 throw new ApplicationException("Fout toevoegen historiek detail: " + ex.Message);
24 }
25 finally
26 {
27 if (oConn.State == ConnectionState.Open) oConn.Close();
28 }
29 }

 
Do i still need the lines 17                   oCmd.CommandText = "select @@IDENTITY";
                                 19                   historiekDetail.HistoriekDetailID = (int)(decimal)oCmd.ExecuteScalar();
Because i've declared the identity in my stored procedure

View 1 Replies View Related

Out Vs. Ref When Calling Stored Procedure

Apr 8, 2008

Hi, I have a stored procedure, and it is expecting an output. If I declared the passing varaible as ref, it compiles fine, but it is not returning any value. If I pass the varaible as out, and add the paramater
MyComm.Parameters.Add(new SqlParameter("@ReturnValue", returnValue));  it gives the following error. 
Compiler Error Message: CS0269: Use of unassigned out parameter 'quoteID'.
 And if I don't supply the previous statement, the following error occurs.
System.Data.SqlClient.SqlException: Procedure 'CreateData' expects parameter '@ReturnValue', which was not supplied.
How Can I fix this? thanks.

View 2 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved