T-SQL (SS2K8) :: Take Data And Execute Stored Procedure With Parameters - Remove Cursor

Jun 26, 2014

I currently have a process that has a cursor. It takes data and executes a stored procedure with parameters.

declare @tmpmsg varchar(max)
declare @tmpmsgprefix varchar(max)
declare @cms varchar(20)
create table #tmpIntegrity(matternum varchar(10),ClientName varchar(20))
insert into #tmpIntegrity(matternum,ClientName)

[Code] ....

Output from code:

The following Client1 accounts have A1 value and a blank A2 field. Accounts: Ac1,Ac2,Ac3,Ac4,
The following Client2 accounts have A1 value and a blank A2 field. Accounts: Ac1,Ac2,Ac3,
The following Client3 accounts have A1 value and a blank A2 field. Accounts: Ac1,Ac2,Ac3,
The following Client4 accounts have A1 value and a blank A2 field. Accounts:

Desired output (no trailing comma):

The following Client1 accounts have A1 value and a blank A2 field. Accounts: Ac1,Ac2,Ac3,Ac4
The following Client2 accounts have A1 value and a blank A2 field. Accounts: Ac1,Ac2,Ac3
The following Client3 accounts have A1 value and a blank A2 field. Accounts: Ac1,Ac2,Ac3
The following Client4 accounts have A1 value and a blank A2 field. Accounts:

Next, how do I call the stored procedure without doing it RBAR? Is that possible?

execute usp_IMessage 832,101,@tmpmsgprefix,@tmpmsg,','

View 5 Replies


ADVERTISEMENT

T-SQL (SS2K8) :: Call Stored Procedure With 3 Parameters

Apr 16, 2014

In t-sql 2008 r2 I need execute a stored procedure called StudentData and pass 3 parameter values to the stored procedure. The stored procedure will then return 5 values that are needed for the main sql. My problem is I do not know how to have the t-sql call the stored procedure with the 3 parameter values and pass back the 5 different unique data values that I am looking for.

The basic dataset is the following:

SELECT SchoolNumber,
SchoolName,
StudentNumber,
from [Trans].[dbo].[Student]
order by SchoolNumber,
SchoolName,
StudentNumber

I basically want to pass the 3 parameters of SchoolNumber, SchoolName, and StudentNumber to the stored procedure called StudentData from the data I obtain from the [Trans].[dbo].[Student]. The 3 parameter values will be obtained from the sql listed above.

The columns that I need from the stored procedure called StudentData will return the following data columns
that I need for the report: StudnentName, StudentAddress, Studentbirthdate, StudentPhoneNumber, GuardianName.

Thus can you show me how to setup the sql to meet this requirement I have?

View 2 Replies View Related

How To Execute A Stored Procedure With Multiple Parameters In VB

Aug 3, 2012

Here is my stored procedure:

ALTER PROCEDURE dbo.SP_UpdateFixedRev
/*
(
@parameter1 int = 5,
@parameter2 datatype OUTPUT
)
*/
(
@Number int,
@FixedRev money
)
AS
BEGIN
/* SET NOCOUNT ON */
Update Ticket set FixedRev = @FixedRev where Number = @Number;
End

Here is my code:

Dim dbConn As New OleDbConnection
Dim dbComm As OleDbCommand
dbConn.ConnectionString = connStr 'connStr is class-level vrbl
dbConn.Open()
dbComm = dbConn.CreateCommand
dbComm.Parameters.Add("@Number", OleDbType.Integer).Value = txtDatabaseTicketNo.Text
dbComm.Parameters.Add("@FixedRev", OleDbType.Currency).Value = txtFixedRev.Text
dbComm.CommandText = "SP_UpdateFixedRev"
dbComm.CommandType = CommandType.StoredProcedure
dbComm.ExecuteNonQuery()
dbConn.Close()

However its not updating my database when I run the app from a button click event.

View 7 Replies View Related

T-SQL (SS2K8) :: Finding Stored Procedure Defaults For Parameters

Jun 2, 2014

I have various ways of getting the parameters of a stored procedure:

I have a procedure that has all defaults 4 are null and 2 are 0.

The following shows most of what I need but no defaults

SELECT PARAMETER_NAME ,
ORDINAL_POSITION ,
DATA_TYPE ,
CHARACTER_MAXIMUM_LENGTH ,
CHARACTER_OCTET_LENGTH ,
NUMERIC_PRECISION ,

[Code] ...

This one has two values:

PARAMETER_HASDEFAULT (always 0) and PARAMETER_DEFAULT (always 0)
sp_procedure_params_rowset proc procedure

Is there something else that would tell me if there is a default on a parameter and what the default is if there is one.

View 2 Replies View Related

Execute Stored Procedure (with Parameters) With An Exec Command

Feb 21, 2004

Hi everybody, I would like to know if it's possible to execute a stored procedure, passing it parameters, using not CommandType.StoredProcedure value of sqlcommand, but CommandType.Text.

I tried to use this:
sqlCmd.CommandType = CommandType.Text
sqlCmd.Parameters.Add(sqlPar)
sqlCmd.ExecuteNonQuery()

With this sql command:
"exec sp ..."

I wasn't able to make it to work, and I don't know if it's possible.

Another question:
if it's not possible, how can I pass a Null value to stored procedure?
This code:
sqlPar = new SqlParameter("@id", SqlDbType.Int)
sqlPar.Direction = ParameterDirection.Output
cmd.Parameters.Add(sqlPar)

sqlPar = new SqlParameter("@parent_id", DBNull)
cmd.Parameters.Add(sqlPar)

doesn't work, 'cause I get this error:
BC30684: 'DBNull' is a type and cannot be used as an expression.

How can I solve this?
Bye and thanks in advance.

P.S. I would prefer first method to call a stored procedure ('cause I could call it with 'exec sp null' sql command, solving the other problem), but obviusly if it's possible...=)

Sorry for grammatical mistakes.

View 9 Replies View Related

Executing Stored Procedure With Parameters Using Execute Sql Task

Jul 12, 2006



Hi ,

I am trying to exectue a stored procedure through execute sql task which takes two input parameters table name and filegroup to create a table and it also returns a value.

i am using the oledb connection

but i am getting the following error



[Execute SQL Task] Error: Executing the query "declare @rtn_value int exec spm_Utopia_FinanceUsage_Create_MonthlyTable ?,? select @rtn_value as rtn_value " failed with the following error: "Syntax error or access violation". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.



i tried with ado.net connection by directly giving the parameter names.

it will create a table but the the table name is something different from what i specified



Please do help as soon as possible



Thanks

Manish



View 2 Replies View Related

SQL 2012 :: SSIS - Execute Stored Procedure With Parameters Does Not Work

Jun 9, 2015

Using the following:

SQL Server: SQL Server 2012
Visual Studio 2012

I have created an SSIS package where I have added an Execute SQL Task to run an existing stored procedure in my SQL database.

General:
Result Set: None
Connection Type: OLE DB
SourceType: Direct Input
IsQueryStoredProcedure: False (this is greyed out and cannot be changed)
Bypass Prepare: True

When I use the following execute statement where I am "Hard Coding" in the parameters, the stored procedure runs successfully and it places the data into the table per the stored procedure.

SQLStatement: dbo.sp_ml_location_load @system_cd='03', @location_type_cd=Store;

However, the @system_cd parameter can change, so I wanted to set these parameters up as variables and use the parameter mapping in the Execute SQL Task.

I have set this up as follows and it runs the package successfully but it does not put the data into the table. The only thing I can figure is either I have the variables set up incorrectly or the parameter mapping set up incorrectly.

Stored procedure variables:

ALTER PROCEDURE [dbo].[sp_ml_location_load]
(@system_cd nvarchar(10), @location_type_cd nvarchar(10))
AS
BEGIN .....................

Here is my set up, what is wrong here:

I Created these Variables:

Name Scope Data Type Value
system_cd Locations String '03'
location_type_cd Locations String Store

I added these parameter mappings in the Execute SQL Task

Variable Name Direction Data TypeParameter NameParameter Size
User::system_cd Input NVARCHAR@system_cd -1
User::location_type_cd Input NVARCHAR@location_type_cd -1

I used this SQLStatement: EXEC dbo.sp_ml_location_load ?,

It runs the package successfully but it does not put the data into the table.

View 2 Replies View Related

T-SQL (SS2K8) :: Passing Multiple Parameters With Table Valued Parameter To Stored Procedure?

May 21, 2014

Can we Pass table valued parameters and normal params like integer,varchar etc..to a single stored procedure?

View 1 Replies View Related

Execute Stored Procedure From Stored Procedure With Parameters

May 16, 2008

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 6 Replies View Related

T-SQL (SS2K8) :: One Stored Procedure Return Data (select Statement) Into Another Stored Procedure

Nov 14, 2014

I am new to work on Sql server,

I have One Stored procedure Sp_Process1, it's returns no of columns dynamically.

Now the Question is i wanted to get the "Sp_Process1" procedure return data into Temporary table in another procedure or some thing.

View 1 Replies View Related

ADO.NET 2-VB 2005 Express Form1:Printing Output Of Returned Data/Parameters From The Parameters Collection Of A Stored Procedure

Mar 12, 2008

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 29 Replies View Related

How Can I Assign A Stored Procedure As Cursor's Data Source In AStored Procedure?

Oct 8, 2007

How can I create a Cursor into a Stored Procedure, with another Stored Procedure as data source?

Something like this:

CREATE PROCEDURE TestHardDisk
AS
BEGIN

DECLARE CURSOR HardDisk_Cursor
FOR Exec xp_FixedDrives
-- The cursor needs a SELECT Statement and no accepts an Stored Procedure as Data Source

OPEN CURSOR HardDisk_Cursor


FETCH NEXT FROM HardDisk_Cursor
INTO @Drive, @Space

WHILE @@FETCH_STATUS = 0
BEGIN

...
END
END

View 6 Replies View Related

T-SQL (SS2K8) :: How To Use Stored Procedure To Query Data In Another Server

May 13, 2014

Say I have to server, A and B.

Now I want to write a stored procedure in server A, to retrieve data from server B.

How could I manage to do that?

View 4 Replies View Related

Java Code To Retrieve Data From Stored Procedure Which Returns Cursor Varying Output?

May 11, 2015

java code to retrieve the data returned by SQL server stored procedure which is of CURSOR VARYING OUTPUT type and display the details on console.

View 3 Replies View Related

Stored Procedure - Returning Data Using Parameters

Feb 12, 2008

Hello,

I am trying to get records related to a Device_ID with the following conditions:

IF LastModified_Date BETWEEN (@p_datetime_StartDate AND @p_datetime_EndDate) OUTPUT
ELSE OUTPUT ALL.

I want records between the range of date selected, or all the records if no date entered. Can somebody help me ASAP. Here is what I have so far. I just don't know where to put the IF...THEN ELSE.

SELECT Device_ID,
Action,
Username,
LastModified_Date,
FROM ActivityMonitorActionLogs
WHERE Device_ID = ISNULL (@p_int_Device_ID, AL.Device_ID)
AND LastModified_Date BETWEEN (@p_datetime_StartDate AND @p_datetime_EndDate)


Thanks a lot!!!
Mylene

View 3 Replies View Related

T-SQL (SS2K8) :: How To Make Code Into Cursor Within Procedure

Feb 3, 2015

i wanna create a procedure for P& L cost sheet , i had done that procedure now include a cursor instead of replacing sql queries .

create procedure pl_test
@fmdate datetime,
@todate datetime,
@categ varchar(2000)
begin
create table #temp

[code]....

how to include cursor on if part and else part

View 2 Replies View Related

SqlDataSource With Stored Procedure With Parameters Returns No Data

Mar 21, 2007

I have a Gridview bound to a SQLDataSource that uses a Stored Procedure expecting 1 or 2 parameters. The parameters are bound to textbox controls. The SP looks up a person by name, the textboxes are Last Name, First Name. It will handle last name only (ie. pass @ln ='Jones' and @fn=null and you get all the people with last name=Jones. I tested the SP in Management Studio and it works as expected. When I enter a last name in the Last Name textbox and no First Name I get no results. If I enter a Last Name AND First Name I get results. I don't understand.
Here's the HTML View of the page. The only code is to bind the Gridview when the Search button is pressed.
<%@ Page Language="VB" AutoEventWireup="true" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server">    <title>Untitled Page</title></head><body>    <form id="form1" runat="server">        <div>            <asp:TextBox ID="TextBox1" runat="server" TabIndex=1></asp:TextBox>&nbsp;            <asp:TextBox ID="TextBox2" runat="server" TabIndex=2></asp:TextBox>&nbsp;            <asp:Button ID="Button1" runat="server" Text="Search" TabIndex=3  />            &nbsp;&nbsp;            <hr />        </div>        <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"    DataSourceID="SqlDataSource1" DataKeyNames="EmpID" CellPadding="4"    EnableSortingAndPagingCallbacks="True" ForeColor="#333333" GridLines="None"    AutoGenerateColumns="False">            <Columns>                <asp:BoundField DataField="EmpID" HeaderText="Emp ID" ReadOnly="True" SortExpression="EmpID" />                <asp:BoundField DataField="FullName" HeaderText="Full Name" SortExpression="FullName" />                <asp:BoundField DataField="Nickname" HeaderText="Nickname" ReadOnly="True" SortExpression="Nickname" />                <asp:BoundField DataField="BGS2" HeaderText="BGS2" SortExpression="BGS2" />                <asp:BoundField DataField="Phone" HeaderText="Phone" SortExpression="Phone" />                <asp:BoundField DataField="email" HeaderText="Email" SortExpression="email" />            </Columns>        </asp:GridView>        <asp:SqlDataSource ID="SqlDataSource1" runat="server"    ConnectionString="<%$ ConnectionStrings:EmpbaseConnectionString %>"            SelectCommand="GetByName" SelectCommandType="StoredProcedure">            <SelectParameters>                <asp:ControlParameter ControlID="TextBox2" Name="fn" PropertyName="Text" Type="String"      ConvertEmptyStringToNull=true/>                <asp:ControlParameter ControlID="TextBox1" Name="ln" PropertyName="Text" Type="String"      ConvertEmptyStringToNull=true/>            </SelectParameters>        </asp:SqlDataSource>    </form>   </body></html>

View 7 Replies View Related

Calling A Stored Procedure On A Data Source (with Parameters)

Nov 29, 2007

This seems to be much more difficult than it was in DTS (or perhaps I just need to adjust to the new way of doing things).

Eventually I found that I needed to use "SQL command from variable" and using two other variables as input parameters. The expresion for the command is

"usp_ValveStatusForDay '" + @[User:ate] + "','" + @[User::Report] + "'"

which typically evaluates as

usp_ValveStatusForDay '18 Oct 07','Report_Name'

This previews correctly and the resulting columns are available for mapping to a destination. So far so good.

By the way, is this the best way to call a stored procedure with parameters?

I have pasted the stored procedure at the end of this posting because I have come accross a puzzling problem. The query as shown below works correctlly but if I un-comment the delete statement, the preview still works and the columns are still avilable for mapping but I get the following errors when the package is executed.


Error: 0xC02092B4 at Data Flow Task, OLE DB Source [1]: A rowset based on the SQL command was not returned by the OLE DB provider.

Error: 0xC004701A at Data Flow Task, DTS.Pipeline: component "OLE DB Source" (1) failed the pre-execute phase and returned error code 0xC02092B4.

I realise that I could execute the delete query in a separate SSIS package step but I am curious as to why there is a problem with the way I tried to do it.

At one stage the stored procedure used a temp table and later I also experimented with a table variable. In both cases I got similar errors at execution time. In the case of the temp table there was another problem in that, while the preview worked, there were no columns available for mapping. Using a table variable seemed to overcome this problem but I still got the run time error. eventually I found a way to avoid using either a temp table or a table variable and the package then worked correctly, copying the data into the desitnation table.

It seems to me that if there is any complexity at all to the stored procedure, these errors seem to occur. Can anyone enlighten me as to what the "rules of engagement" are in this regard? Is one solution to use a wrapper stored procedure that simply calls the more complex one?



ALTER procedure [dbo].[usp_ValveStatusForDay]

(

@dateTime DateTime,

@reportName VarChar(100)

)

AS

BEGIN

DECLARE @day VarChar(10)

DECLARE @month VarChar(10)

DECLARE @year VarChar(10)

DECLARE @start VarChar(25)

DECLARE @end VarChar(25)

SET @day = Convert(Varchar(10),DatePart(day, @dateTime))

SET @month = Convert(VarChar(10), DatePart(month, @dateTime))

SET @year = Convert(VarChar(10), DatePart(year, @dateTime))

IF @month = '1' SET @month = 'Jan'

IF @month = '2' SET @month = 'Feb'

IF @month = '3' SET @month = 'Mar'

IF @month = '4' SET @month = 'Apr'

IF @month = '5' SET @month = 'May'

IF @month = '6' SET @month = 'Jun'

IF @month = '7' SET @month = 'Jul'

IF @month = '8' SET @month = 'Aug'

IF @month = '9' SET @month = 'Sep'

IF @month = '10' SET @month = 'Oct'

IF @month = '11' SET @month = 'Nov'

IF @month = '12' SET @month = 'Dec'

SET @start = @day + ' ' + @month + ' ' + @year + ' 00:00:00'

SET @end = @day + ' ' + @month + ' ' + @year + ' 23:59:59'

--delete from ValveStatus where SampleDateTime between dbo.ToBigInt(@start) and dbo.ToBigInt(@end)

exec dbo.usp_ValveStats_ReportName @reportName, @start, @end, '1h'

END

View 8 Replies View Related

Data Migration Script - Execute Stored Procedure Set-based

Sep 18, 2013

I am writing a number of data migration scripts, like the (simplified version) below

Code:
INSERT INTO newDatabase.dbo.DaDestinationTable(col1, col2, col3)
SELECT col1,
col27,
col13
FROM OldDatabase.dbo.DaSourceTable

There are no validation rules defined in the database (don't ask why), only in the program code. Because of the absence of validations in the database, the data migration scripts could violate business rules (NOT NULL, FK violations, domain values in a column, ...).

A solution could be that both the program and the data migration call the same stored procedure to insert records in the destination table, so the validation rules must only be defined in one place (the stored procedure).

I have never used stored procedures in a "set-based" situation. Is this even possible? The only solution I see is to call those sp's in a loop (WHILE or CURSOR). Something like

Code:
SET @my_id = -1
SELECT @my_id = MIN(id)
FROM OldDatabase.dbo.DaSourceTable
WHERE id > @my_id
WHILE @my_id IS NOT NULL

[Code] ....

For each record, the table OldDatabase.dbo.DaSourceTable is hit twice, once to get the next id (@my_id), once to get the column values. I could combine both with one SELECT script by using ROW_NUMBER(), but I doubt that that will perform faster.

I only work set-based, I have barely ever used a WHILE loop, let alone a CURSOR. What the consequences will be on performance. There are millions of records that have to be migrated.

I was thinking of CROSS APPLY, but you can't use that in combination with a SP.

View 6 Replies View Related

Pass Large Data Into Stored Procedure Using Execute SQL Task

Jan 15, 2008

Dear All!
I use a "Execute SQL Task" to call a Stored Procedure. My Stored Procedure have an input parameter with type: ntext. And in "Execute SQL Task", I set variable in Parameter Mapping as following:

Variable Name: User::xmlDocument (this variable is a String to store xml data)
Direction: Input
DataType: NVARCHAR
ParameterName: 0


When length of "User::xmlDocument" is too large then error is happen but on the contrary, "Execute SQL Task" run successfully.
So, Can you show me how to pass large data into stored procedure using "Execute SQL Task"?
I am looking forward to hearing from you
Thanks

View 20 Replies View Related

User Defined Data Type Used In Stored Procedure Parameters

Jul 23, 2005

I have several stored procedures with parameters that are defined withuser defined data types. The time it takes to run the procedures cantake 10 - 50 seconds depending on the procedure.If I change the parameter data types to the actual data type such asvarchar(10), etc., the stored procedure takes less that a second toreturn records. The user defined types are mostly varchar, but someothers such as int. They are all input type parameters.Any ideas on why the stored procedure would run much faster if notusing user defined types?Using SQL Server 2000.Thanks,DW

View 13 Replies View Related

What Is Wrong With This Code? Selecting Data With Stored Procedure With Multiple Parameters

Sep 22, 2005

oConn = New SqlClient.SqlConnection
oConn.ConnectionString = "user id=MyUserID;data source=MyDataSource;persist security info=False;initial catalog=DBname;password=password;"
oCmd = New SqlClient.SqlCommand
oCmd.Connection = oConn
oCmd.CommandType = CommandType.StoredProcedure
oCmd.CommandText = "TestStdInfo"
'parameters block
oParam1 = New SqlClient.SqlParameter("@intSchoolID", Me.ddlSchl.SelectedItem.ToString())
oParam1.Direction = ParameterDirection.Input
oParam1.SqlDbType = SqlDbType.Int
oCmd.Parameters.Add(oParam1)
oParam2 = New SqlClient.SqlParameter("@dob", Convert.ToDateTime(Me.txbBirth.Text))
oParam2.Direction = ParameterDirection.Input
oParam2.SqlDbType = SqlDbType.DateTime
oCmd.Parameters.Add(oParam2)
oParam3 = New SqlClient.SqlParameter("@id", Me.txbID.Text)
oParam3.Direction = ParameterDirection.Input
oParam3.SqlDbType = SqlDbType.VarChar
oCmd.Parameters.Add(oParam3)
oConn.Open()
daStudent = New SqlClient.SqlDataAdapter("TestStdInfo", oConn)
dsStudent = New DataSet
daStudent.Fill(dsStudent)  'This line is highlighted when error happens
oConn.Close()The error I am getting :Exception Details: System.Data.SqlClient.SqlException: Procedure 'TestStdInfo' expects parameter '@intSchoolID', which was not supplied.I am able to see the value during debugging in the autos or command window. Where does it dissapear when it comes to Fill?Could anybody help me with this, if possible fix my code or show the clean code where the procedure called with multiple parameters and dataset filled.Thank you so much for your help.

View 2 Replies View Related

SQL 2012 :: SSIS Passing Parameters To Stored Procedure That Changes Based On The Data Being Passed?

Jun 23, 2015

Using the following:

SQL Server: SQL Server 2012
Visual Studio 2012

I have created an SSIS package where I have added an Execute SQL Task to run an existing stored procedure in my SQL database.

General Tab:

Result Set: None
Connection Type: OLE DB
SourceType: Direct Input
IsQueryStoredProcedure: False (this is greyed out and cannot be changed)
Bypass Prepare: True
SQL Statement: EXEC FL_CUSTOM_sp_ml_location_load ?, ?;

Parameter Mapping:

Variable Name Direction Data Type Prmtr Name Prmtr Size
User: system_cd Input NVARCHAR 0 10
User: location_type_cd Input NVARCHAR 1 10

Variables:

location_type_cd - Data type - string; Value - Store (this is static)
system_cd - Data type - string - ??????
The system code changes based on the system field for each record in the load table

Sample Data:

SysStr # Str_Nm
3 7421Store1
3 7454Store2
1815061Store3
1815063Store4
1615064Store5
1615065Store6
1615066Store7
7725155Store8

STORED PROCEDURE: The stored procedure takes data from a load table and inserts it into another table:

Stored procedure variables:
ALTER PROCEDURE [dbo].[sp_ml_location_load]
(@system_cd nvarchar(10), @location_type_cd nvarchar(10))
AS
BEGIN .....................

This is an example of what I want to accomplish: I need to be able to group all system 3 records, then pass 3 as the parameter for system_cd, run the stored procedure for those records, then group all system 18 records, then pass 18 as the parameter for system_cd, run the stored procedure for those records and keep doing this for each different system in the table until all records are processed.

I am not sure how or if it can be done to pass the system parameter to the stored procedure based on the system # in the sys field of the data.

View 6 Replies View Related

SQL Reporting Services Issue Using Multiple Parameters Where Data Is Passed In From A Stored Procedure

Apr 15, 2008



I have an issue with using multiple parameters in SQL Reporting services where data is passed in from a stored procedure



When running the report in design mode - I can type in a parameter sting and it runs fine



In the report preview screen I can select single parameters by ticking the drop down list and again it runs fine



as soon as I tick more than one I get an error



An error occurred during local report processing

Query execution failed for data set €˜data'

Must declare the scalar variable '@parameter'



Some info...



The dataset 'workshop' is using a sproc to return the data string?

I get multiple values back fine in the sproc using this piece of code

(select [str] from iter_charlist_to_table( @Parameter, DEFAULT) ))



I have report parameters set to Multi-Value

Looking through the online books it says...



You can define a multivalued parameter for any report parameter that you create.

However, if you want to pass multiple parameter values back to a query, the following requirements must be satisfied:

The data source must be SQL Server, Oracle, or Analysis Services.
The data source cannot be a stored procedure. Reporting Services does not support passing a multivalued parameter array to a stored procedure.
The query must use an IN clause to specify the parameter.

Am I trying to do the impossible ?

View 1 Replies View Related

SSIS Hard Time Getting Back XML Return Data From Stored Procedure Call Executed By Execute SQL Task

Aug 9, 2006

I'm having a hard time to getting back an xml data back from a stored procedure executed by an Execute SQL task.

I'm passing in an XML data as a parameter and getting back resulting XML data as a parameter. The Execute SQL task is using ADO connection to do this job. The two parameters(in/out) are type of "string" and mapped as string.

When I execute the task, I get the following error message.

[Execute SQL Task] Error: Executing the query "dbo.PromissorPLEDataUpload" failed with the following error: "The incoming tabular data stream (TDS) remote procedure call (RPC) protocol stream is incorrect. Parameter 2 ("@LogXML"): Data type 0xE7 has an invalid data length or metadata length.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.

I also tried mapping the parameter as XML type, but that didn't work either.

If anyone knows what's going on or how to fix this problem please let me know. All I want to do is save returning XML data in the parameter to a local package variable.

Thanks

View 10 Replies View Related

T-SQL (SS2K8) :: Varbinary (max) Parameters In Nested Stored Procedures By Value Or Reference

Sep 15, 2014

Consider a situation where a stored procedure taking a varbinary(max) (BLOB) input parameter then calls a nested stored procedure and passes along that varbinary(max) as an input parameter to the nested stored procedure.

Is a copy of the BLOB provided to the nested stored procedure (passed by value) OR is the BLOB passed by reference.

My interest is in understanding the potential memory hit when handling large BLOBs in this environment.

For example, if the BLOB is 200MB, will SQL server need to allocate memory for a new copy each time it's passed to another stored procedure?

Looks like table type parameters are passed by reference, but I haven't been able to find any info on BLOBS in this context.

View 8 Replies View Related

Remove Columns Stored Procedure

May 6, 2007

Just wondering if i could get some help with this,

I have a large table of decimal values, many of the columns contain only zero values. I would like to write a
stored procedure which loops through these columns, takes the SUM and if it returns zero , then deletes the column from the table.

Any help would be appreciated, thanks in advance, this site has already helped me heaps

View 14 Replies View Related

Cursor With Stored Procedure

Aug 11, 2004

I have a stored procedure that basically recieves the where clause of a select statement and executes the new sql statement... ie:

CREATE PROCEDURE [dbo].[bsa_GetImportIDs]
(@FilterText varchar(1000))
AS

DECLARE @MySQL varchar(1000)

SET @MySQL = "SELECT Import_ID FROM tblImport WHERE " + @FilterText

EXEC (@MySQL)
GO

Now, in another stored procedure, I need to use the stored procedure above in a cursor so that I can execute an insert statement for each occurance of the Import_ID that appears in that dataset... ie:

CREATE PROCEDURE [dbo].[bsa_PutLargeCase]
AS

DECLARE @CaseID uniqueidentifier
SET @CaseID = NewID()
Declare @ImportID uniqueidentifier

Declare curClient Cursor FAST_FORWARD for
SELECT Import_ID FROM dbo.bsa_GetImportIDs (@FilterText) <---- this does not work!!!

Open curClient
FETCH NEXT FROM curClient INTO @ImportID
WHILE @@FETCH_STATUS = 0
BEGIN

EXEC dbo.bsa_PutCaseDetail @CaseID, @ImportID

FETCH NEXT FROM curClient INTO @ImportID
END

CLOSE curClient
DEALLOCATE curClient

GO

How can I utilize my first stored procedure in the cursor of the second? ... or
Are there any other approaches that may be a better solution to what I am trying to accomplish?

Thanks in advance for any input.

View 2 Replies View Related

Out A Cursor From A Stored Procedure

Aug 17, 2000

hello!

any of you have an idea how i can declare an output parameter for my cursor which is inside a stored procedure. i would lik to see the output using the exec command but i don't know how to get the out from my cursor.
please help!

honey

View 1 Replies View Related

Stored Procedure Into A Cursor

Jul 20, 2005

Hi guys!!I am trying to fill a cursor with the results of a StoredProcedured, but SQL give me an syntax error message , does any one cangive me some helpI am using SQL Server, this is the first lines of my codeDECLARE FRates_Cursor CURSOR FORexec GET_FJRs_Eng 'all'OPEN FRates_Cursorif I run just the exec GET_FJRs_Eng 'all' line it give me the dataresults I am trying to put into the cursor, what that means is thestored is working fineThanks in advance

View 2 Replies View Related

Execute SQL Store_procedure Using XML's Data As Parameters

Nov 27, 2005

I want to learn how can achieve as the subject say, thanks!

View 4 Replies View Related

How To Remove The Commented Notes In Stored Procedure?

Oct 14, 2005

Hello, everyone:

There are some commented notes in the stored procedure from clients. Is there any way to remove these notes automatically, I mean using scripts etc.

Thanks

ZYT

View 5 Replies View Related

User 'Unknown User' Could Not Execute Stored Procedure - Debugging Stored Procedure Using Visual Studio .net

Sep 13, 2007

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 3 Replies View Related







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