How To Test Stored Procedure With Output Parameters In Management Studio
I have this SP:
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[GetSessionInformation]
@CustomerID int,
@Success bit OUTPUT,
@Email VarChar(55) OUTPUT,
@FirstName VarChar(55) OUTPUT,
@LastName VarChar(50) OUTPUT,
@PhoneNumber VarChar(50) OUTPUT,
@CompanyName VarChar(50) OUTPUT
AS
SET NOCOUNT ON
DECLARE @UserKey AS int
SELECT @CustomerID = CustomerID
FROM Customers
WHERE CustomerID = @CustomerID
IF @CustomerID IS NULL
BEGIN
SET @Success = 0
END
ELSE
BEGIN
SET @Success = 1
END
BEGIN
SELECT customerID, Email, FirstName, LastName, PhoneNumber, CompanyName
FROM Customers
WHERE CustomerID = @UserKey
How do I test it in management studio?
When I run a EXECUTE GetSessionInformation 56
I get this error:
Procedure 'GetSessionInformation' expects parameter '@Success', which was not supplied.
Thanks for any help!
View Complete Forum Thread with Replies
Related Forum Messages:
ADO.NET 2-VB 2005 Express Form1:Printing Output Of Returned Data/Parameters From The Parameters Collection Of A Stored Procedure
Hi all, From the "How to Call a Parameterized Stored Procedure by Using ADO.NET and Visual Basic.NET" in http://support.microsft.com/kb/308049, I copied the following code to a project "pubsTestProc1.vb" of my VB 2005 Express Windows Application: Imports System.Data Imports System.Data.SqlClient Imports System.Data.SqlDbType Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim PubsConn As SqlConnection = New SqlConnection("Data Source=.SQLEXPRESS;integrated security=sspi;" & "initial Catalog=pubs;") Dim testCMD As SqlCommand = New SqlCommand("TestProcedure", PubsConn) testCMD.CommandType = CommandType.StoredProcedure Dim RetValue As SqlParameter = testCMD.Parameters.Add("RetValue", SqlDbType.Int) 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 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// The original article uses the code statements in pink for the Console Applcation of VB.NET. I do not know how to print out the output of ("Book Titles for this Author:"), ("{0}", myReader.GetString(2)), ("Return Value: " & (RetValue.Value)) and ("Number of Records: " & (NumTitles.Value)) in the Windows Application Form1 of my VB 2005 Express. Please help and advise. Thanks in advance, Scott Chang
View Replies !
Stored Procedure With Output Parameters
i built a stored procedure with inserting in to customers table. i have one column with identity. so want to take that identity column value in the same stored procedure. so how can i write that procedure with insert in to statements in that stored procedures. can any one tell me. also how to get that value in ado.net 2.0. friends please tell me.
View Replies !
Stored Procedure And Output Parameters
EXEC('SELECT COUNT(docid) AS Total FROM docs WHERE ' + @QueryFilter)I want to get the cound as an output parameter.I can get output parameters to work only when I dont use EXEC. I need to use EXEC for this case since @QueryFilter gets generated in the stored procedure based on some some other data.How can I get that count using ouput parameter?
View Replies !
Stored Procedure Output Parameters
Hi I've an existing SQL 2000 Stored Procedure that return data in many (~20) output parameters. I'm starting to use it in a .Net c# application and it seems to insist that I setup all the output parameters: SqlParameter param = cmd.Parameters.Add("@BackgroundColour",SqlDbType.TinyInt); param.Direction=ParameterDirection.Output; even if I only need the value of a single one. Is this right? Is there a way to avoid coding every one every time?
View Replies !
OUT And OUTPUT - Stored Procedure Parameters.
Hi All, The following is a code snippit. My main interests are the OUT and OUTPUT parameter keywords. One returns a single value, and the other seemingly a resultset. OUTPUT returns a single value, however OUT seems to return a list of values. Could I please get this confirmed? Also, I cannot see how the value being returned by OUT is being iterated... Any help on the obove two matters is appreciated. Thank You Chris BEGIN SNIPPET---------------------------------------------------------------------------------------------------------- --The following example creates the Production.usp_GetList --stored procedure, which returns a list of products that have --prices that do not exceed a specified amount. USE AdventureWorks; GO IF OBJECT_ID ( 'Production.uspGetList', 'P' ) IS NOT NULL DROP PROCEDURE Production.uspGetList; GO CREATE PROCEDURE Production.uspGetList @Product varchar(40) , @MaxPrice money , @ComparePrice money OUTPUT , @ListPrice money OUT AS SELECT p.[Name] AS Product, p.ListPrice AS 'List Price' FROM Production.Product AS p JOIN Production.ProductSubcategory AS s ON p.ProductSubcategoryID = s.ProductSubcategoryID WHERE s.[Name] LIKE @Product AND p.ListPrice < @MaxPrice; -- Populate the output variable @ListPprice. SET @ListPrice = (SELECT MAX(p.ListPrice) FROM Production.Product AS p JOIN Production.ProductSubcategory AS s ON p.ProductSubcategoryID = s.ProductSubcategoryID WHERE s.[Name] LIKE @Product AND p.ListPrice < @MaxPrice); -- Populate the output variable @compareprice. SET @ComparePrice = @MaxPrice; GO --- USE DECLARE @ComparePrice money, @Cost money EXECUTE Production.uspGetList '%Bikes%', 700, @ComparePrice OUT, @Cost OUTPUT IF @Cost <= @ComparePrice BEGIN PRINT 'These products can be purchased for less than $'+RTRIM(CAST(@ComparePrice AS varchar(20)))+'.' END ELSE PRINT 'The prices for all products in this category exceed $'+ RTRIM(CAST(@ComparePrice AS varchar(20)))+'.' ---------------------- --- Partial Result Set ---------------------- --Product List Price ---------------------------------------------------- ------------------ --Road-750 Black, 58 539.99 --Mountain-500 Silver, 40 564.99 --Mountain-500 Silver, 42 564.99 --... --Road-750 Black, 48 539.99 --Road-750 Black, 52 539.99 -- --(14 row(s) affected) -- --These items can be purchased for less than $700.00.
View Replies !
Stored Procedure And Output Parameters
Hi, I hope someone can help. I've written a stored procedure that returns a value via an output parameter. I'm calling the stored procedure in an sql session is a loop, and it passes the value back correctly the first time, but all subsequent calls the output parameter appears to have the same value. I believe that I'm making some very basic mistake, but I can't work it out. Here's how I'm calling the stored procedure several times begin declare @instrumentid int exec GetInstrumentId 'OFX,AUDCHF,p,1,2007-03-20 16:54:21.843,2007-06-20,100.1', @instrumentid output; select @instrumentid exec GetInstrumentId 'OFX,AUDUSD,c,2,2007-03-20 16:54:21.843,2007-06-20,100.2', @instrumentid output; select @instrumentid exec GetInstrumentId 'OFX,AUDCHF,p,3,2007-03-20 16:54:21.843,2007-06-20,100.3', @instrumentid output; select @instrumentid end And this is the start of the stored procedure Create PROCEDURE [dbo].[GetInstrumentId] (@Ticket varchar(250), @InstrumentId int output) AS If I call the stored procedure once it gives the corect output, if I call it several times the output parameter (@instrumentid ) never changes. Sean
View Replies !
How To Extract Output Parameters From A Stored Procedure.
I am stuck on how to syntactically retrieve an output value (@ProdCount) from a stored procedure. The SPROC works fine: the value of @ProdCount appears correctly in the output window. However, I can't retrieve it in the DAL handler (value remains 0). Does anyone have an idea on how to properly extract the return value. TIA for any pointers.SPROC (abridged): ALTER PROCEDURE and_Store_GetProductsByProdCatID_SortPage (@ProdCatID INT,...@ProdCount INT OUTPUT ) ASSELECT @ProdCount=(SELECT COUNT(*) FROM and_StoreProduct WHERE ProdCatID= @ProdCatID)DECLARE @SQL nvarchar(4000)SET @SQL = 'WITH tmpProd AS ( SELECT ROW_NUMBER() etc.. )SELECT ProdID, etc..FROM tmpProdWHERE Row BETWEEN etc..ORDER BY etc..' EXECUTE(@SQL)RETURNDAL handler (abridged): Public Overloads Shared Function GetProductListByCatID(ByVal ProdCatID As Integer, ..., ByVal ProdCount As Integer) As List(Of Product) Dim productList As List(Of Product) = New List(Of Product) Try Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("conAnders").ConnectionString) Dim cmd As SqlCommand = New SqlCommand("and_Store_GetProductsByProdCatID_SortPage", con) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.AddWithValue("@ProdCatID", ProdCatID) '... cmd.Parameters.AddWithValue("@ProdCount", ProdCount) ' Output parm. Add dummy value. Dim objProduct As Product 'Temp Product. con.Open() Using myReader As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection) While myReader.Read() objProduct = New Product() With objProduct .ProdID = myReader.GetInt32(myReader.GetOrdinal("ProdID")) 'etc.. End With productList.Add(objProduct) End While Dim tmp As Object = cmd.Parameters("@ProdCount").Value ' <-- Not updated myReader.Close() End Using End Using Catch ex As Exception Throw ' Pass up the error. End Try Return productList End Function
View Replies !
How To Save A Stored Procedure With Management Studio?
Hi, i can make and save a stored procedure in Visual Web Developer (via Database Explorer). It appears then in the list op stored procedure in Management Sudio. But how to do the same in Management Studio? When i make a sp and i want to save it, Management Studio asks me a name, but put the file in a Projects directory in 'My documents'. It never appears in the list of sp. Thanks tartuffe
View Replies !
Issue With NULLs And Output Parameters In A Stored Procedure.
I am trying to set up a stored procedure to return details about an item in my database. Say I use the following declarations for a stored procedure: @Parameter1 int output, @Parameter2 varchar(200) output, @Parameter3 int output and then I used a query like: select @Parameter1 = table.field1, @Parameter2 = table.field2, @Parameter3 = table.field3 from table where itemID = 7 to populate the output parameters the problem I am running into is that if @Parameter1 is null, then @Parameter2 and @Parameter3 also return as null. But, If i rewrite the declarations to: @Parameter3 int output, @Parameter2 varchar(200) output, @Parameter1 int output then, with the same query, @Parameter3 and @Parameter2 get the values they should, even if @Parameter1 is null does anyone have any ideas? I guess another question is, I am right now in the code itself (not the demonstration here) returning 6 values, since this procedure will only ever return one record, I decided to implement it as output variables, rather than returning a 1 record result set to the application. Am I better off just returning the 1 record result set then parsing it out into variables in the application? Thanks in advance -madrak
View Replies !
Binding Stored Procedure OUTPUT Parameters To A TextBox, How?
Hi all; How can I show the Name & Age of the selected student's ID in the appropriate TextBox(s) (txtName & txtAge)? BTW: My "ShowStudent" stored procedure: ALTER PROCEDURE ShowStudent @ID int AS SELECT ID, Name, Age FROM Student WHERE ID=@ID RETURN And this is the code for "Show" button: ' Which SP? Connection? Dim cmdSelect As New SqlCommand("ShowStudent", con) cmdSelect.CommandType = CommandType.StoredProcedure '-----[ Spacifay SP parameters ]----- 'ID cmdSelect.Parameters.Add("@ID", SqlDbType.Int, 4) cmdSelect.Parameters("@ID").Value = CType(txtID.Text, Integer) 'Open Connection con.Open() '-----[ Execute the select command ]----- cmdSelect.ExecuteReader() '---------------------------------------- 'Close connection con.Close() '======================================================== End Sub So, do I have to use an OUTPUT parameter in the stored procedure? If Yes, How to get its (the parameter) value and bind it to the appropriate TextBox? Hope my question is clear!! Thanks in advanced!
View Replies !
Esql/C Calling Stored Procedure With Output Parameters
I'm trying to write an esqlc program that will run a stored procedure that returns several output parameters. I haven't been able to find any documentation to date that explains how to run the "EXEC SQL EXECUTE procname" command and specify the output parameters. My stored procedure "aek_proc1" takes one input parameter (p1 - an 8-character string) and 3 output parameters (p2 - an integer; p3 - an 8-character string, and p4 a 40-character string). My esqlc program contains the following code…. EXEC SQL BEGIN DECLARE SECTION; char p1[9]; int p2; char p3[9]; char p4[41]; WXEC SQL END DECLARE SECTION; sprintf(&p1[0], "GL"); p2 = 0; sprintf(&p3[0], ""); sprintf(&p4[0], ""); EXEC SQL EXECUTE aek_proc1 :p1, :p2 OUTPUT, :p3 OUTPUT, :p4 OUTPUT; I am getting errors at runtime about constants being passed for OUTPUT parameters. I can run the same stored procedure in Query Analyser and it works beautifully (see below) declare @p1 char(8) declare @p2 integer declare @p3 char(8) declare @p4 char(40) set @p1 = 'GL' execute aek_proc1 @p1, @p2 output, @p3 output, @p4 output select @p1 p1, @p2 p2, @p3 p3, @p4 p4 Any idea what I'm doing wrong or how it should be coded? I'd really appreciate any advice you can offer!! I've spend hours browsing this newsgroup and found lots of examples of how to do this in VB and from Query Analyser but I can't find any examples for ESQL/C that work. So, please help!!! Thanks, AllanK :rolleyes:
View Replies !
Strings As Stored Procedure Output Parameters (ODBC)
I'd very much appreciate if someone could point me in the right direction. I can not retrieve string as output parameter from SQL Server Express 2005 stored procedure. Stored proc DDL is following: CREATE PROCEDURE storedProcedure (@inParam VARCHAR(MAX), @outParam VARCHAR(MAX) OUTPUT) AS BEGIN SET @outParam = @inParam; END; ODBC code SQLExecDirect(hstmt1, (UCHAR*)"{call storedProcedure(?,?)}", SQL_NTS); fails with this error: [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid parameter 2 (''): Data type 0x23 is a deprecated large object, or LOB, but is marked as output parameter. Deprecated types are not supported as output parameters. Use current large object types instead. And here is the full code (derived from a sample at CodePlex): #include <stdio.h> #include <string.h> #include <windows.h> #include <sql.h> #include <sqlext.h> #include <odbcss.h> #define MAXBUFLEN 255 SQLHENV henv = SQL_NULL_HENV; SQLHDBC hdbc1 = SQL_NULL_HDBC; SQLHSTMT hstmt1 = SQL_NULL_HSTMT; void Cleanup() { if (hstmt1 != SQL_NULL_HSTMT) SQLFreeHandle(SQL_HANDLE_STMT, hstmt1); if (hdbc1 != SQL_NULL_HDBC) { SQLDisconnect(hdbc1); SQLFreeHandle(SQL_HANDLE_DBC, hdbc1); } if (henv != SQL_NULL_HENV) SQLFreeHandle(SQL_HANDLE_ENV, henv); } int main() { RETCODE retcode; // SQLBindParameter variables. SQLCHAR* sParm1 = (SQLCHAR*) "123"; SQLCHAR sParm2[10] = {0}; SQLLEN cbParm1 = SQL_NTS; SQLLEN cbParm2 = SQL_NTS; // Allocate the ODBC environment and save handle. retcode = SQLAllocHandle (SQL_HANDLE_ENV, NULL, &henv); if ( (retcode != SQL_SUCCESS_WITH_INFO) && (retcode != SQL_SUCCESS)) { printf("SQLAllocHandle(Env) Failed"); Cleanup(); return(9); } // Notify ODBC that this is an ODBC 3.0 app. retcode = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3, SQL_IS_INTEGER); if ( (retcode != SQL_SUCCESS_WITH_INFO) && (retcode != SQL_SUCCESS)) { printf("SQLSetEnvAttr(ODBC version) Failed"); Cleanup(); return(9); } // Allocate ODBC connection handle and connect. retcode = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc1); if ( (retcode != SQL_SUCCESS_WITH_INFO) && (retcode != SQL_SUCCESS)) { printf("SQLAllocHandle(hdbc1) Failed"); Cleanup(); return(9); } // Connect. SQLCHAR connectOutput[512] = {0}; SQLSMALLINT result; retcode = SQLDriverConnect(hdbc1, NULL, (UCHAR*) "DRIVER=SQL Server;" "UID=test;" "PWD=test;" "DATABASE=test;" "SERVER=localhost;", (SQLSMALLINT) SQL_NTS , connectOutput , sizeof(connectOutput) , &result , SQL_DRIVER_NOPROMPT); if ( (retcode != SQL_SUCCESS) && (retcode != SQL_SUCCESS_WITH_INFO) ) { printf("SQLConnect() Failed"); Cleanup(); return(9); } // Allocate statement handle. retcode = SQLAllocHandle(SQL_HANDLE_STMT, hdbc1, &hstmt1); if ( (retcode != SQL_SUCCESS) && (retcode != SQL_SUCCESS_WITH_INFO) ) { printf("SQLAllocHandle(hstmt1) Failed"); Cleanup(); return(9); } // Create the stored procedure. retcode = SQLExecDirect(hstmt1, (UCHAR*)"CREATE PROCEDURE storedProcedure(@inParam VARCHAR(MAX), @outParam VARCHAR(MAX) OUTPUT) AS " "BEGIN " "SET @outParam = @inParam; " "END;", SQL_NTS); if ( (retcode != SQL_SUCCESS) && (retcode != SQL_SUCCESS_WITH_INFO) ) { printf("SQLExecDirect Failed"); Cleanup(); return(9); } // Bind the return code to variable sParm1. retcode = SQLBindParameter(hstmt1, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_LONGVARCHAR, 3, 0, sParm1, 0, &cbParm1); if ( (retcode != SQL_SUCCESS) && (retcode != SQL_SUCCESS_WITH_INFO) ) { printf("SQLBindParameter(sParm1) Failed"); Cleanup(); return(9); } // Bind the output parameter to variable sParm2. retcode = SQLBindParameter(hstmt1, 2, SQL_PARAM_OUTPUT, SQL_C_CHAR, SQL_LONGVARCHAR, 10, 0, sParm2, 0, &cbParm2); if ( (retcode != SQL_SUCCESS) && (retcode != SQL_SUCCESS_WITH_INFO) ) { printf("SQLBindParameter(sParm2) Failed"); Cleanup(); return(9); } // Execute the command. retcode = SQLExecDirect(hstmt1, (UCHAR*)"{call storedProcedure(?,?)}", SQL_NTS); if ( (retcode != SQL_SUCCESS) && (retcode != SQL_SUCCESS_WITH_INFO) ) { SQLSMALLINT count = 0; SQLSMALLINT messageLength = 0; SQLCHAR sqlState[SQL_SQLSTATE_SIZE + 1]; SQLCHAR message[SQL_MAX_MESSAGE_LENGTH]; SQLINTEGER nativeError; while(SQL_SUCCEEDED(SQLGetDiagRec(SQL_HANDLE_STMT, hstmt1, ++count, sqlState, &nativeError, message, sizeof(message), &messageLength))) { printf("%s", message); } Cleanup(); return(9); } // Show parameters are not filled. printf("Before result sets cleared: RetCode = %d, OutParm = %d.", sParm1, sParm2); // Clear any result sets generated. while ( ( retcode = SQLMoreResults(hstmt1) ) != SQL_NO_DATA ) ; // Show parameters are now filled. printf("After result sets drained: RetCode = %d, OutParm = %d.", sParm1, sParm2); // Drop the procedure. retcode = SQLExecDirect(hstmt1, (UCHAR*)"DROP PROCEDURE storedProcedure;", SQL_NTS); if ( (retcode != SQL_SUCCESS) && (retcode != SQL_SUCCESS_WITH_INFO) ) { printf("SQLExecDirect Failed"); Cleanup(); return(9); } // Clean up. SQLFreeHandle(SQL_HANDLE_STMT, hstmt1); SQLDisconnect(hdbc1); SQLFreeHandle(SQL_HANDLE_DBC, hdbc1); SQLFreeHandle(SQL_HANDLE_ENV, henv); } Thank you, Alex
View Replies !
Stored Procedure:high Number Of Output Parameters
If I want to get back about 30 strings as output parameters from a stored procedure, what is my best bet? Each string is upto 50 characters each. Do I send them back individually as seperate parameters? Return as a large parsed string? Return as XML? Thanks!
View Replies !
Executing Oracle Stored Procedure With Output Parameters Using ADO.NET Connection
I am a bit confused by an issue that I am having with executing an Oracle stored procedure (with an output parameter) using an ADO.NET connection object. I am able to get this working using an OLEDB connection, but I have no idea why the ADO.NET connection doesn't work. (Bug, by design, or my ignorance?) Actually, I can even get this to work if I use the .NET Providers for OLE DBMicrosoft OLE DB Provider for ORACLE if we set the connectionType to ADO.NET. This is the error that I am receiving: [Execute SQL Task] Error: Executing the query "pkg_utility_read.test_out_var " failed with the following error: "The OracleParameterCollection only accepts non-null OracleParameter type objects, not SqlParameter objects.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly. It is also worth mentioning that the ORACLE stored procedure has an out parameter with a NUMBER datatype which I think maps to the ADO.NET Int32 datatype. I guess OLE DB datatypes are more closely mapped to ORACLE datatypes. In OLE DB you can set the parameter to double and the ORACLE stored procedure to NUMBER and it works. Any help on this would be most appriciated.
View Replies !
How Do I Create A Stored Procedure In SQL Server Management Studio Express?
I have wrriten many stored procedures in the past without issue, but this is my first time using SQL Server Management Studio Express. I am having trouble creating a new stored procedure. Here is what's happening: I am opening my database, right clicking on "Stored Procedures" and selecting "New Stored Procedure". A new window opens with a template for creating a stored procedure. The window is called: "SQLEXPRESS.DBName - sqlquery1.sql". I then type up my stored procedure without an issue. However, when I go to save the stored procedure it wants to save it as a separate file in a projects folder. It does not become part of the DB (as far as I can tell). When I used to use Enterprise Manager (not an option anymore) this never happened. I'm sure I'm doing something dumb. Can someone enlighten me. Thanks,Chris
View Replies !
Attaching A Stored Procedure To A Database In MS SQL Server Management Studio
Hello all! Quick question... I've created my DB in MSSQLSMS, then attempted to created a stored procedure for it. The code itself is fine, I just need to know how to actually attach it so that it appears in the "Stored Procedures" section of my Database. I have Right Clicked on Stored Procedures > New Stored Procedure... > Edited as required > Save When I attempt to save it, it prompts me for a file. That's fine, did that - but I can't see ANY way to actually attach this to the DB. Any help is appreciated! Daniel Davies
View Replies !
How To Empty A Stored Procedure In Ms Sql Server Management Studio Express
hi everyone, I have a db based on the Tracking_Schema.sql / Tracking_Logic.sql (find in &windir%/Microsoft.NET/Framework/v3.0/Windows Workflow Foundation/SQL/EN), so after executing both of them I get several stored procedures, especially dbo.GetWorkflows. And I have a solution in VS05 which when executed is filling this stored procedure with Instance-Id´s. My question is: how is the working command (like exec, truncate,..) to empty my st.procedure, not to drop/delete it? Thanks in advance, best regards bg
View Replies !
Stored Procedure Not Returning OUTPUT Parameters To Visual Basic Program
I have coded a stored procedure to return nearly all of the columns of a single record selected by using a unique key value. The record is in an SQL database, not within an in-memory DataSet. All of the parameters that I wish to have returned to my program are defined as OUTPUT; the two key values are defaulted to INPUT, as there is no need to return them to the calling program. I also have defined the direction of these parameters in the calling SQLDataAdapter function. However, when I run this, the values returned are either the current date for my DateTime parameters, Nothing for my Char parameters or 0's for my integer parameters. When I try testing the sproc alone, by using the "Step Into Stored Procedure" action in Visual Studio, I get a message in the Debug Output window indicating that parameter @TktClassID was expected and not supplied. This is an OUTPUT parameter, which makes me question why I should be providing any sort of value for it within my VB code. Following are the function definition from my SQLDataAdapter class that calls my sproc, and the sproc itself. I appreciate any help that anyone can provide. **FUNCTION DEFINITION FROM SQLDataAdapter Class Public Function Fetch(ByVal ticket As Ticket) As Ticket Dim connbuilder As New System.Data.SqlClient.SqlConnectionStringBuilder connbuilder("Data Source") = "ITS-KCGV7VZSQLEXPRESS" connbuilder("Integrated Security") = "True" connbuilder("Initial Catalog") = "ITSHelpDesk" Using conn As New System.Data.SqlClient.SqlConnection(connbuilder.ConnectionString) Using comm As New System.Data.SqlClient.SqlCommand("dbo.TicketFetch", conn) conn.Open() comm.CommandType = CommandType.StoredProcedure Dim parm As System.Data.SqlClient.SqlParameter 'Add Input parameters (i.e. Key values) 'Add @TicketYear parameter parm = comm.Parameters.Add("@TicketYear", SqlDbType.SmallInt) parm.Value = DBNull.Value parm.Direction = ParameterDirection.Input 'Add @TicketID parameter parm = comm.Parameters.Add("@TicketID", SqlDbType.Int) parm.Value = DBNull.Value parm.Direction = ParameterDirection.Input 'Add Output parameters 'Add @TktClassID parameter parm = comm.Parameters.Add("@TktClassID", SqlDbType.SmallInt) parm.Direction = ParameterDirection.Output parm.SourceColumn = ticket.TktClassID 'Add @TktRequestTypeID parameter parm = comm.Parameters.Add("@TktRequestTypeID", SqlDbType.SmallInt) parm.Direction = ParameterDirection.Output parm.SourceColumn = ticket.TktRequestTypeID 'Add @DateOpened parameter parm = comm.Parameters.Add("@DateOpened", SqlDbType.DateTime) parm.Direction = ParameterDirection.Output parm.SourceColumn = ticket.DateOpened 'Add @DateClosed parameter parm = comm.Parameters.Add("@DateClosed", SqlDbType.DateTime) parm.Direction = ParameterDirection.Output parm.SourceColumn = ticket.DateClosed 'Add @DateLastAssigned parameter parm = comm.Parameters.Add("@DateLastAssigned", SqlDbType.DateTime) parm.Direction = ParameterDirection.Output parm.SourceColumn = ticket.DateLastAssigned 'Add @DateLastStatusChange parameter parm = comm.Parameters.Add("@DateLastStatusChange", SqlDbType.DateTime) parm.Direction = ParameterDirection.Output parm.SourceColumn = ticket.DateLastStatusChange 'Add @TktStatus parameter parm = comm.Parameters.Add("@TktStatusID", SqlDbType.SmallInt) parm.Direction = ParameterDirection.Output parm.SourceColumn = ticket.TktStatusID 'Add @DescrRequest parameter parm = comm.Parameters.Add("@DescrRequest", SqlDbType.VarChar) parm.Direction = ParameterDirection.Output parm.SourceColumn = ticket.DescrRequest 'Add @DescrResolution parameter parm = comm.Parameters.Add("@DescrResolution", SqlDbType.VarChar) parm.Direction = ParameterDirection.Output parm.SourceColumn = ticket.DescrResolution parm.Value = " " 'Handle bug? 'Add @OpenStatus parameter parm = comm.Parameters.Add("@OpenStatus", SqlDbType.Bit) parm.Direction = ParameterDirection.Output parm.SourceColumn = ticket.OpenStatus 'Add @UserLastUpdate parameter parm = comm.Parameters.Add("@UserLastUpdate", SqlDbType.Char) parm.Direction = ParameterDirection.Output parm.SourceColumn = ticket.UserLastUpdate 'Add @DateLastUpdate parameter parm = comm.Parameters.Add("@DateLastUpdate", SqlDbType.DateTime) parm.Direction = ParameterDirection.Output parm.SourceColumn = ticket.DateLastUpdate comm.ExecuteNonQuery() End Using End Using Return ticket End Function **STORED PROCEDURE DEFINITION USE [ITSHelpDesk] GO /****** Object: StoredProcedure [dbo].[TicketFetch] Script Date: 03/24/2008 08:40:53 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: Tim Peters -- Create date: 3/17/2008 -- Description: Fetch Ticket from Ticket table -- ============================================= ALTER PROCEDURE [dbo].[TicketFetch] -- Add the parameters for the stored procedure here @TicketYear smallint = 0, @TicketID int = 0, @TktClassID smallint = NULL OUTPUT, @TktRequestTypeID smallint = NULL OUTPUT, @DateOpened datetime = NULL OUTPUT, @DateClosed datetime = NULL OUTPUT, @DateLastAssigned datetime = NULL OUTPUT, @DateLastStatusChange datetime = NULL OUTPUT, @TktStatusID smallint = NULL OUTPUT, @DescrRequest varchar(500) = NULL OUTPUT, @DescrResolution varchar(500) = NULL OUTPUT, @OpenStatus bit = NULL OUTPUT, @UserLastUpdate char(10) = NULL OUTPUT, @DateLastUpdate datetime = NULL OUTPUT AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; -- Insert statements for procedure here SELECT @TktClassID = [TktClassID], @TktRequestTypeID = [TktRequestTypeID], @DateOpened = [DateOpened], @DateClosed = [DateClosed], @DateLastAssigned = [DateLastAssigned], @DateLastStatusChange = [DateLastStatusChange], @TktStatusID = [TktStatusID], @DescrRequest = [DescrRequest], @DescrResolution = [DescrResolution], @OpenStatus = [OpenStatus], @UserLastUpdate = [UserLastUpdate], @DateLastUpdate = [DateLastUpdate] FROM [dbo].[Ticket] WHERE [TicketYear] = @TicketYear AND [TicketID] = @TicketID END RETURN
View Replies !
Testing A Stored Procedure With Output Params In SQL Server Managment Studio
I have an SP like this (edited for brevity): set ANSI_NULLS ON set QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[TESTING_SP] @Username MediumText, @Password MediumText, @UserKey int OUTPUT, @RoleKey int OUTPUT, @UserGroupKey int OUTPUT, AS BEGIN SELECT @UserKey = UserKey FROM UserProfile WHERE Username = @UserName AND [Password] = @Password END I want to execute this sp in Managment Studio (MS) and see what is being returned but I'm getting this error: Msg 201, Level 16, State 4, Procedure TESTING_SP, Line 0 Procedure 'TESTING_SP' expects parameter '@UserKey', which was not supplied. How do I set up the output parameters and then select the values in MS for testing purposes? Thanks a ton for helping a noob.
View Replies !
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
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 Replies !
Accessing A Stored Procedure From ADO.NET 2.0-VB 2005 Express:How To Define/add 1 Output && 2 Input Parameters In Param. Coll.?
Hi all, In a Database "AP" of my SQL Server Management Studio Express (SSMSE), I have a stored procedure "spInvTotal3": CREATE PROC [dbo].[spInvTotal3] @InvTotal money OUTPUT, @DateVar smalldatetime = NULL, @VendorVar varchar(40) = '%' This stored procedure "spInvTotal3" worked nicely and I got the Results: My Invoice Total = $2,211.01 in my SSMSE by using either of 2 sets of the following EXEC code: (1) USE AP GO --Code that passes the parameters by position DECLARE @MyInvTotal money EXEC spInvTotal3 @MyInvTotal OUTPUT, '2006-06-01', 'P%' PRINT 'My Invoice Total = $' + CONVERT(varchar,@MyInvTotal,1) GO (2) USE AP GO DECLARE @InvTotal as money EXEC spInvTotal3 @InvTotal = @InvTotal OUTPUT, @DateVar = '2006-06-01', @VendorVar = '%' SELECT @InvTotal GO //////////////////////////////////////////////////////////////////////////////////////////// Now, I want to print out the result of @InvTotal OUTPUT in the Windows Application of my ADO.NET 2.0-VB 2005 Express programming. I have created a project "spInvTotal.vb" in my VB 2005 Express with the following code: Imports System.Data Imports System.Data.SqlClient Imports System.Data.SqlTypes Public Class Form1 Public Sub printMyInvTotal() Dim connectionString As String = "Data Source=.SQLEXPRESS; Initial Catalog=AP; Integrated Security=SSPI;" Dim conn As SqlConnection = New SqlConnection(connectionString) Try conn.Open() Dim cmd As New SqlCommand cmd.Connection = conn cmd.CommandType = CommandType.StoredProcedure cmd.CommandText = "[dbo].[spInvTotal3]" Dim param As New SqlParameter("@InvTotal", SqlDbType.Money) param.Direction = ParameterDirection.Output cmd.Parameters.Add(param) cmd.ExecuteNonQuery() 'Print out the InvTotal in TextBox1 TextBox1.Text = param.Value Catch ex As Exception MessageBox.Show(ex.Message) Throw Finally conn.Close() End Try End Sub End Class ///////////////////////////////////////////////////////////////////// I executed the above code and I got no errors, no warnings and no output in the TextBox1 for the result of "InvTotal"!!?? I have 4 questions to ask for solving the problems in this project: #1 Question: I do not know how to do the "DataBinding" for "Name" in the "Text.Box1". How can I do it? #2 Question: Did I set the CommandType property of the command object to CommandType.StoredProcedure correctly? #3 Question: How can I define the 1 output parameter (@InvTotal) and 2 input parameters (@DateVar and @VendorVar), add them to the Parameters Collection of the command object, and set their values before I execute the command? #4 Question: If I miss anything in print out the result for this project, what do I miss? Please help and advise. Thanks in advance, Scott Chang
View Replies !
Built Database With SQL Server Management Studio Express, How Can I Quikly Add Test Data?
I've built my SQL Server Express database with SQL Serevr Management Studio Express, and now I want to enter some seed data to assist in building tha app around it. I cannot find an option to manage the data in SQL SMSX, like I used to with Enterprise Manager. I don't want to have to write an app just to get test data in. Seems like this should be a common need. Am I missing something obvious here? Can't find any reference to this in a search of the forums. Please help.
View Replies !
T-SQL And Visual Basic 2005 Codes That Execute A User-Defined Stored Procedure In Management Studio Express (Part 2)
Hi Jonathan Kehayias, Thanks for your valuable response. I had a hard time to sumbit my reply in that original thread yesterday. So I created this new thread. Here is my response to the last code/instruction you gave me: I corrected a small mistake (on Integrated Security-SSPI and executed the last code you gave me. I got the following debug error message: 1) A Box appeared and said: String or binary data would be truncated. The statement has been terminated. |OK| 2) After I clicked on the |OK| button, the following message appeared: This "SqlException was unhandled String or binary data would be truncated. The statement has been terminated." is pointing to the "Throw" code statement in the middle of ....................................... Catch ex As Exception MessageBox.Show(ex.Message) Throw Finally .......... Please help and advise how to correct this problem in my project that is executed in my VB 2005 Express-SQL Server Management Studio Express PC. Thanks, Scott Chang The code of my Form1.vb is listed below: Imports System.Data Imports System.Data.SqlClient Imports System.Data.SqlTypes Public Class Form1 Public Sub InsertNewFriend() Dim connectionString As String = "Data Source=.SQLEXPRESS;Initial Catalog=shcDB;Integrated Security=SSPI;" Dim connection As SqlConnection = New SqlConnection(connectionString) Try connection.Open() Dim command As SqlCommand = New SqlCommand("sp_insertNewRecord", connection) command.CommandType = CommandType.StoredProcedure command.Parameters.Add("@procPersonID", SqlDbType.Int).Value = 7 command.Parameters.Add("@procFirstName", SqlDbType.NVarChar).Value = "Craig" command.Parameters.Add("@procLastName", SqlDbType.NVarChar).Value = "Utley" command.Parameters.Add("@procAddress", SqlDbType.NVarChar).Value = "5577 Baltimore Ave" command.Parameters.Add("@procCity", SqlDbType.NVarChar).Value = "Ellicott City" command.Parameters.Add("@procState", SqlDbType.NVarChar).Value = "MD" command.Parameters.Add("@procZipCode", SqlDbType.NVarChar).Value = "21045" command.Parameters.Add("@procEmail", SqlDbType.NVarChar).Value = "CraigUtley@yahoo.com" Dim resulting As String = command.ExecuteNonQuery MessageBox.Show("Row inserted: " + resulting) Catch ex As Exception MessageBox.Show(ex.Message) Throw Finally connection.Close() End Try End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load InsertNewFriend() End Sub End Class
View Replies !
T-SQL And Visual Basic 2005 Codes That Execute A User-Defined Stored Procedure In Management Studio:How To Declare EXEC && Sp?
Hi all, In my SQL Server Management Studio Express (SSMSE), I executed the following sql code suuccessfully: --insertNewRocord.sql-- USE shcDB GO CREATE PROC sp_insertNewRecord @procPersonID int, @procFirstName nvarchar(20), @procLastName nvarchar(20), @procAddress nvarchar(50), @procCity nvarchar(20), @procState nvarchar(20), @procZipCode nvarchar(20), @procEmail nvarchar(50) AS INSERT INTO MyFriends VALUES (@procPersonID, @procFirstName, @procLastName, @procAddress, @procCity, @procState, @procZipCode, @procEmail) GO EXEC sp_insertNewRecord 7, 'Peter', 'Wang', '678 Old St', 'Detroit', 'Michigon', '67899', 'PeterWang@yahoo.com' GO ======================================================================= Now, I want to insert a new record into the dbo.Friends table of my shcDB by executing the following T-SQL and Visual Basic 2005 codes that are programmed in a VB2005 Express project "CallshcDBspWithAdoNet": --Form1.vb-- Imports System.Data Imports System.Data.SqlClient Imports System.Data.SqlTypes Public Class Form1 Public Sub InsertNewFriend() Dim connectionString As String = "Integrated Security-SSPI;Persist Security Info=False;" + _ "Initial Catalog=shcDB;Data Source=.SQLEXPRESS" Dim connection As SqlConnection = New SqlConnection(connectionString) connection.Open() Try Dim command As SqlCommand = New SqlCommand("sp_InsertNewRecord", connection) command.CommandType = CommandType.StoredProcedure EXEC sp_insertNewRecord 6, 'Craig', 'Utley', '5577 Baltimore Ave', 'Ellicott City', 'MD', '21045', 'CraigUtley@yahoo.com' Console.WriteLine("Row inserted: " + _ command.ExecuteNonQuery().ToString) Catch ex As Exception Console.WriteLine(ex.Message) Throw Finally connection.Close() End Try End Sub End Class =========================================================== I ran the above project in VB 2005 Express and I got the following 5 errors: 1. Name 'EXEC' is not declared (in Line 16 of Form1.vb) 2. Method arguments must be enclosed in parentheses (in Line 16 of Form1.vb) 3. Name 'sd-insertNewRecord' is not declared. (in Line 16 of Form1.vb) 4.Comma, ')', or a valid expression continuation expected (in Line 16 of Form1.vb) 5. Expression expected (in Line 16 of Form1.vb) ============================================================ I know that "EXEC sp_insertNewRecord 6, 'Craig', 'Utley', '5577 Baltimore Ave', 'Ellicott City', 'MD', '21045', 'CraigUtley@yahoo.com' "in Line 16 of Form1.vb is grossly in error. But I am new in doing the programming of T-SQL in VB 2005 Express and I am not able to change it. Please help and advise me how to correct these problems. Thanks in advance, Scott Chang
View Replies !
SQL Server Management Studio Express Output
I am trying to get information on how to change the output from SQL Server Management. The output I get is seems to have FF FE at the beginning of the file. Also has 00 after each character. You can't see them unless you edit in hex editor. They do not appear when edited in notepad. Please reply!!! I can't understand why so many look at this but no one has any suggestions. Am I in the wrong place or is this to stupid of a question to posted?
View Replies !
MDX Query With Parameters In Management Studio
Hello, I would like to know if it is possible to make a MDX query on a cube with parameters in Management Studio and if yes, how to define the parameters? In fact, I have a quite big query which of course does not work and in Reporting Services, I get an error message which is not very clear : Cannot set the command text for data set "Cube" Error during processing of the CommandText expression of dataset "Cube" So I would like to test my query in SSMS and correct directly. Edit : Forget the query but my question concerning the parameters definition in SSMS is still asked. Thanks
View Replies !
Default Output Encoding For Management Studio 2005
Hi All, Not sure if this is the right place to ask but.. Our company has just migrated to 2005 from 2000. I've got Management Studio doing much of what I need it to do from the old enterprise manager (which I wish I could go back to). My problem is this. When saving CSV files from a script run inside Management Studio (ad hoc reports, custom queries, etc) the default encoding is to UNICODE. This produces files that excel doesn't handle very well (most of the people I'd be sending the results to would freak out when the CSV file doesn't appear as expected). I've discovered that I can change the encoding to ANSI when I save the query but as it's a manual process I'm sure I'm going to get tired of it very quickly. I would really like to make ANSI encoding the default. (at the moment and for the foreseeable future, we don't need the functionality that Unicode provides). Anyone know how to do this -- I've tried searching the docs without success. Thanks All, Charlie. ------------- Charlie
View Replies !
Using Output From A Stored Procedure As An Output Column In The OLE DB Command Transformation
I am working on an OLAP modeled database. I have a Lookup Transformation that matches the natural key of a dimension member and returns the dimension key for that member (surrogate key pipeline stuff). I am using an OLE DB Command as the Error flow of the Lookup Transformation to insert an "Inferred Member" (new row) into a dimension table if the Lookup fails. The OLE DB Command calls a stored procedure (dbo.InsertNewDimensionMember) that inserts the new member and returns the key of the new member (using scope_identity) as an output. What is the syntax in the SQL Command line of the OLE DB Command Transformation to set the output of the stored procedure as an Output Column? I know that I can 1) add a second Lookup with "Enable memory restriction" on (no caching) in the Success data flow after the OLE DB Command, 2) find the newly inserted member, and 3) Union both Lookup results together, but this is a large dimension table (several million rows) and searching for the newly inserted dimension member seems excessive, especially since I have the ID I want returned as output from the stored procedure that inserted it. Thanks in advance for any assistance you can provide.
View Replies !
How To Get Store Procedure's Return Value And Output Parameters From BLL?
ex: myprocedure(@Cusname varchar(50), @Cusid int output)as Insert into Customer(Cusname) values (@Cusname)SELECT @cusid = @@IDENTITY i add the query to my adapter called CreatCustomer (@Cusnam,@Cusid)private Merp_CusListTableAdapter _CuslistAdapter = null;protected Merp_CusListTableAdapter Adapter { get {if (_CuslistAdapter == null) _CuslistAdapter = new Merp_CusListTableAdapter();return _CuslistAdapter; } } Now how i write function in BLL to receive output paramter from creatcustomer function?
View Replies !
Some Problems With Output Parameters In Stored Procedures
I have written a simple C# console application that create my own Stored Procedures the code is here ---------------------------------------------------------------------------- static void Main(string[] args) { SqlConnection cn; string strSql; string strConnection; SqlCommand cmd; strConnection="server=(local);database=Northwind;integrated security=true;"; strSql="CREATE PROCEDURE spmahdi @CustomerID nchar(5) @counter int OUTPUT AS SELECT OrderID, OrderDate,RequiredDate,ShippedDate FROM Orders WHERE CustomerID = @CustomerID ORDER BY OrderID SET @counter=@@rowcount"; cn=new SqlConnection(strConnection); cn.Open(); cmd=new SqlCommand(strSql,cn); cmd.ExecuteNonQuery(); cn.Close(); Console.WriteLine("Procedure Created!"); } ------------------------------------------------------------------------------------ but it has some errors becuase of my strSql strSql="CREATE PROCEDURE spmahdi @CustomerID nchar(5) @counter int OUTPUT AS SELECT OrderID, OrderDate,RequiredDate,ShippedDate FROM Orders WHERE CustomerID = @CustomerID ORDER BY OrderID SET @counter=@@rowcount"; I mean in creating the stored procedure if i delete the Output parameter from my stored procedure and my strSql would be somethimg like this strSql="CREATE PROCEDURE spmahdi @CustomerID nchar(5) AS SELECT OrderID, OrderDate,RequiredDate,ShippedDate FROM Orders WHERE CustomerID = @CustomerID ORDER BY OrderID "; There will be no errors I use Visual Studio.NET 2003(full versoin)and MSDE(not Sql Server) Could someone help me solve this problem? Thanks and Regards.
View Replies !
Different Results When Running Procedure From Management Studio Vs Application Code
I'm updating a process that recreates a large table every night. The table is the result of a bunch of nightly batch processes and holds a couple million records. In the past, each night at the end of the batch jobs the table would be dropped and re-created with the new data. This process was embodied in dynamic sql statements from an MFC C++ program, and my task is to move it to a SQL Server 2000 stored procedure that will be called from a .Net app. Here's the relevant code from my procedure: sql Code: Original - sql Code -- recreate new empty BatchTable table print 'Dropping old BatchTable table...' exec DropBatchTable --stored procedure called from old code that does a little extra work when dropping the table -- validate drop If exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BatchTable]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) Begin RAISERROR( 'Unable to drop old BatchTable!',0,1) WITH NOWAIT End Else Begin print 'Old BatchTable dropped.' End print 'Creating new BatchTable...' SELECT TOP 0 *, cast('' as char(3)) as Client, cast('' as char(12)) as ClientDB INTO dbo.BatchTable FROM differentDB.dbo.BatchArchives --validate create If Not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BatchTable]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) Begin RAISERROR( 'Unable to create new BatchTable!',0,1) WITH NOWAIT End Else Begin print 'New BatchTable Created.' End -- recreate new empty BatchTable table print 'Dropping old BatchTable table...' exec DropBatchTable --stored procedure called from old code that does a little extra work when dropping the table -- validate drop IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[BatchTable]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN RAISERROR( 'Unable to drop old BatchTable!',0,1) WITH NOWAIT END ELSE BEGIN print 'Old BatchTable dropped.' END print 'Creating new BatchTable...' SELECT TOP 0 *, CAST('' AS CHAR(3)) AS Client, CAST('' AS CHAR(12)) AS ClientDB INTO dbo.BatchTable FROM differentDB.dbo.BatchArchives --validate create IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[BatchTable]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN RAISERROR( 'Unable to create new BatchTable!',0,1) WITH NOWAIT END ELSE BEGIN print 'New BatchTable Created.' END The print statements are there because the .net app will read them in and then write them to a log file. Some of the other mechanics are there to mimic the old process. The idea is to duplicate the old process first and then work on other improvements. This works in Management studio. The .Net App reports that the old table was dropped, but when it tries to create the new table it complains that "There is already an object named 'BatchTable' in the database." I have verified that the old table is removed. Any ideas on how to fix this?
View Replies !
Bug In Management Studio : Cannot Add Procedure Article For Heterogeneous Transactional Replication
Hi, I'm setting up a heterogeneous transactional push replication with Sybase ASE 12.5.3 as subscriber. With management studio I try to create an procedure article with following properties Copy extended properties : false Destination object name : pGS_RefuseRequest Destination object ownere : dbo Action if name is in use : keep existing object unchanged Replicate : Execution of the stored procedure Create schemas at Subscriber : false When I save the article and then the publication I got following error message: Can not add artice 'pGS_RefuseRequest'. Object was not found on server. Check if this object exists on the server. (Microsoft.SqlServer.Rmo) That's realy strange because the wizard offered the procedure pGS_RefuseRequest in the list of possible articles. Fortunatly I can create the article with following TSQL statement : exec sp_addarticle @publication = N'RIGHTS_EDV_4T_pub' , @article = N'pGS_RefuseRequest' , @source_owner = N'dbo' , @source_object = N'pGS_RefuseRequest' , @type = N'proc exec' , @description = N'' , @creation_script = N'' , @pre_creation_cmd = N'none' , @schema_option = 0x00 , @destination_table = N'pGS_RefuseRequest' , @destination_owner = N'dbo' , @status = 0 go Did anybody seen this bug before ? It seems to be specific for heterogeneuous replication. In a pure MS environement the Wizard works fine! Wolfgang Kunk
View Replies !
Output Parameters Versus Recordsets In Stored Procedures
I've read that stored procedures should use output parameters instead ofrecordsets where possible for best efficiency. Unfortunately I need toquantify this with some hard data and I'm not sure which counters touse. Should I be looking at the SQL Server memory counters or somethingelse.*** Sent via Developersdex http://www.developersdex.com ***Don't just participate in USENET...get rewarded for it!
View Replies !
Stored Procedures Not Showing In Server Management Studio
i'm trying to create my first stored procedure. i believe i've done everything correctly, the file shows up in the projects directory with the .sql extension, but the proc doesnt appear in object explorer under my database name/programmability/stored procedures. when i execute the query, i get "Could not find stored procedure 'IsEmployeeInTable'.". i'm running on my laptop using asp.net development server. thanks. matt
View Replies !
MS SQL Server Management Studio - Permissions And Stored Procedures
Hi My website uses GET variables a lot and i'm trying to safe guard as much as possible against SQL injection attacks. I'm trying to create permissions which will deny a user to Delete/Insert/Update various tables. I have managed this with the tables themselves, but when using a stored procedure, the tables do not take into account the user permissions which were set for that table! Basically, how do i stop a stored procedure from Deleting/Inserting/Updating tables? :( many thanks
View Replies !
Test If A Table Exists Then Create A Stored Procedure?
Point of reference: I am very new to sql so if it is something obvious... Also i removed the guts of the sp (too long and irrelevant) if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[TABLE1]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE PROCEDURE isp_calc_totals ......... GO SET QUOTED_IDENTIFIER OFF GO SET ANSI_NULLS ON GO END
View Replies !
Stored Procedures Management - Keeping Input Parameters Updated
Hi everyone I have just starting creating some stored procedures for our system and have a question related to management of these. When using input parameters using the following syntax: CREATE PROCEDURE sp_someInputProcedure @Username as varchar(16) @Password as varchar(12) @Name as varchar(50) @Address as varchar(60) @Zip as int @City as varchar(30) ... etc. This is all well and good, but what if I make a change in the datamodel - for instance changing a datatype or the length of a varchar - do I need to remember to manually update all stored procedures that uses these columns/variables? Seems like a bit of a hazzle. Is there an easier way to do this? Many thanks, Stian Danielsen Epizone
View Replies !
What Is The Security Setting To Allow Editing Of Stored Procedures From Management Studio?
Greetings Running SQL Server 2005. The developers on the project can see and edit stored procedures from within the Visual Studio IDE (via Server Explorer) but when they connect through management studio, the stored procedures do not show up at all. Is there a seperate security setting specifically for management studio? The user has: The dbCreator Server Role Is mapped to the development database as dbo with datareader/datawriter/db owner/public role Is mapped to master reader/writer/public Is mapped to model reader/writer public Is mapped to msdb reader/writer public Is mapped to tempdb reader/writer publuc This is probably more security than the user needs, but was grasping at straws to let them edit stored procedures...
View Replies !
Stored Procedure Passes Test In Gridview, But Nothing Shows Up On The Page
Like the subject says I have tested the SP in Gridview. Everything looks fine. But when run nothing shows up on the page. I have tried using QueryStrings to pass the data and Controls. Here is the Gridview Code:<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" CellPadding="4" DataSourceID="SqlDataSource1"> <FooterStyle BackColor="#99CCCC" ForeColor="#003399" /> <RowStyle BackColor="White" ForeColor="#003399" /> <Columns><asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" /><asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" /><asp:BoundField DataField="EthnicID" HeaderText="EthnicID" SortExpression="EthnicID" /><asp:BoundField DataField="Gender" HeaderText="Gender" SortExpression="Gender" /><asp:BoundField DataField="Height" HeaderText="Height" SortExpression="Height" /><asp:BoundField DataField="Weight" HeaderText="Weight" SortExpression="Weight" /> <asp:BoundField DataField="Hair" HeaderText="Hair" SortExpression="Hair" /> <asp:BoundField DataField="Eyes" HeaderText="Eyes" SortExpression="Eyes" /> <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" /> <asp:BoundField DataField="State" HeaderText="State" SortExpression="State" /> </Columns> <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" /> <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" /> <HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" /> </asp:GridView> Here is the Datasource:<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:SQL2005_311004_modelsystemConnectionString %>" SelectCommand="spSearch" SelectCommandType="StoredProcedure"> <SelectParameters><asp:QueryStringParameter DefaultValue="" Name="FirstName" QueryStringField="fn" Type="String" /> <asp:QueryStringParameter Name="LastName" QueryStringField="ln" Type="String" /> <asp:Parameter Name="EthnicID" Type="String" /> <asp:Parameter Name="Gender" Type="String" /> <asp:Parameter Name="Height" Type="String" /> <asp:Parameter Name="weight" Type="String" /> <asp:Parameter Name="Hair" Type="String" /> <asp:Parameter Name="Eyes" Type="String" /> <asp:Parameter Name="City" Type="String" /> <asp:Parameter Name="State" Type="String" /> </SelectParameters> </asp:SqlDataSource> I hope you can help me with this one!!!
View Replies !
Viewing Large Numbers Of Stored Procs In SQL Server Management Studio
I work with a large and complex reporting system with several hundred reports: the Programmability; Stored Procedures node of the object explorer has become very difficult to navigate. Is there any metadata that can be embedded in the stored procs that would create subfolders like the existing System Stored Procedures node in this node of the object explorer? I suspect that the correct answers are: Rename all your queries with a rational naming convention; Cull the deadwood; Assign them to categories then export them to separate databases. Unfortunately, one of these has already been done, and the other two will break several hundred dependent processes - the recoding and retesting is neither economical nor desirable. Still, all advice is welcome. Pitch your answers at a banking geek who does intermediate to advanced stored procedures and triggers, but isn't allowed to play with sharp things (like sys objects) - but I can probably get help from a grown-up on the sysadmin team: I have discovered that the rumours about human sacrifice are baseless, and they will perform favours in return for beer. This is also a good time to ask: just how many stored procs and functions are you allowed in SQL Server 2005? Nile.
View Replies !
User 'Unknown User' Could Not Execute Stored Procedure - Debugging Stored Procedure Using Visual Studio .net
Hi all, I am trying to debug stored procedure using visual studio. I right click on connection and checked 'Allow SQL/CLR debugging' .. the store procedure is not local and is on sql server. Whenever I tried to right click stored procedure and select step into store procedure> i get following error "User 'Unknown user' could not execute stored procedure 'master.dbo.sp_enable_sql_debug' on SQL server XXXXX. Click Help for more information" I am not sure what needs to be done on sql server side We tried to search for sp_enable_sql_debug but I could not find this stored procedure under master. Some web page I came accross says that "I must have an administratorial rights to debug" but I am not sure what does that mean? Please advise.. Thank You
View Replies !
Learn To Access Stored Procedures With ADO.NET 2.0-VB 2005:How To Work With Output Parameters && Report Their Values In VB Forms?
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 Replies !
Execute Stored Procedure From Stored Procedure With Parameters
Hello, I am hoping there is a solution within SQL that work for this instead of making round trips from the front end. I have a stored procedure that is called from the front-end(USP_DistinctBalancePoolByCompanyCurrency) that accepts two parameters and returns one column of data possibly several rows. I have a second stored procedure(USP_BalanceDateByAccountPool) that accepts the previous stored procedures return values. What I would like to do is call the first stored procedure from the front end and return the results from the second stored procedure. Since it's likely I will have more than row of data, can I loop the second passing each value returned from the first? The Stored Procs are: CREATE PROCEDURE USP_DistinctBalancePoolByCompanyCurrency @CID int, @CY char(3) AS SELECT Distinct S.BalancePoolName FROM SiteRef S INNER JOIN Account A ON A.PoolId=S.ID Inner JOIN AccountBalance AB ON A.Id = AB.AccountId Inner JOIN AccountPool AP On AP.Id=A.PoolId Where A.CompanyId=@CID And AB.Currency=@CY CREATE PROCEDURE USP_BalanceDateByAccountPool @PoolName varchar(50) AS Declare @DT datetime Select @DT= (Select MAX(AccountBalance.DateX) From Company Company INNER JOIN Account Account ON Company.Id = Account.CompanyId INNER JOIN SiteRef SiteRef ON Account.PoolId = SiteRef.ID Inner JOIN AccountBalance AccountBalance ON Account.Id = AccountBalance.AccountId WHERE SiteRef.BalancePoolName = @PoolName) SELECT SiteRef.BalancePoolName, AccountBalance.DateX, AccountBalance.Balance FROM Company Company INNER JOIN Account Account ON Company.Id = Account.CompanyId INNER JOIN SiteRef SiteRef ON Account.PoolId = SiteRef.ID Inner JOIN AccountBalance AccountBalance ON Account.Id = AccountBalance.AccountId WHERE SiteRef.BalancePoolName = @PoolName And AccountBalance.DateX = @DT Order By AccountBalance.DateX DESC Any assistance would be greatly appreciated. Thank you, Dave
View Replies !
Output Stored Procedure
1 public static List<string> viewtree(int root) 2 { 3 SqlConnection con = new SqlConnection(mainConnectionString); 4 con.Open(); 5 try 6 { 7 List<string> ids = new List<string>(); 8 SqlCommand command = new SqlCommand(@"ShowHierarchy2", con); 9 command.Parameters.AddWithValue("@root", root); 10 command.Parameters.Add(new SqlParameter("@outstring", SqlDbType.VarChar)); 11 command.Parameters["@outstring"].Direction = ParameterDirection.Output; 12 command.CommandType = CommandType.StoredProcedure; 13 //command.ExecuteScalar(); 14 //ids = command.Parameters["@outstring"].Value.ToString(); 15 16 SqlDataReader dr = command.ExecuteReader(); 17 while (dr.Read()) 18 { 19 ids.Add((dr["@outstring"].ToString())); 20 } 21 //command.Parameters.Clear(); 22 23 return ids; 24 } 25 finally 26 { 27 con.Close(); 28 } 29 } Can someone tell me why i'm getting the following error:String[1]: the Size property has an invalid size of 0. Thanks in advance
View Replies !
How To Get Stored Procedure Output ?
I have a variable @NetPay as type money, and a stored proc spGetNetPay. The output of spGetNetPay has one column NetPay, also with type of money, and always has one row. Now I need assgin output from spGetNetPay to user variable @NetPay. How can I do That? Set @NetPay = (Exec spGetNetPay) Sorry this does not work. Is it possible to create a user defined function? I have little knowledge about User defided function. Is is the way I should go? Thanks. David J.
View Replies !
Output Stored Procedure
Dear All,How can I show the resultrecords of a SP.I can be done by doubleclick the SPname?But how to do it by code.I want the following interfaceIn my form the user1 selects a SP (combobox showing a userfrinly name)2 adds the related parameters3 and then click the show result-buttonbut the .execute command doen't show teh records.I want the same output as you have doublclicking the SPname in theobjectwindow.Thanks,Filip
View Replies !
Immediate Output From Stored Procedure.
When I run a script in query analyzer using a script (A "GO" statement exists after each SQL) I get the results on screen as soon as each query completes. When I run thru stored proc, I can get the result only after the whole procedure completes execution. Is there any way to get the outpout immediately as soon as each query completes? This will be useful in tracking thre progress of a stored proc. Thanks Satish
View Replies !
|