Showing posts with label proc. Show all posts
Showing posts with label proc. Show all posts

Thursday, March 29, 2012

Executing SSIS from stored procedure - need to get return value into ASP.NET

I'm executing an SSIS package using the following stored procedure

ALTER PROC [dbo].[SSISRunBuildSCCDW]ASBEGINDECLARE @.ServerNameVARCHAR(30), @.ReturnValueint, @.Cmdvarchar(1000)SET @.ReturnValue = -1SET @.ServerName ='myserver'SET @.Cmd ='DTExec /SER ' + @.ServerName +' ' +' /SQL ' +'\BuildSCCDW '--Location of the package stored in the mdb --' /CONF "\\ConfigFilePath.dtsConfig" ' +--' /SET \Package.Variables[ImportUserID].Value; ' +--' /U "LoginName" /P "password" 'EXECUTE @.ReturnValue = master..xp_cmdshell @.Cmd, NO_OUTPUTRETURN @.ReturnValue--SELECT @.ReturnValue [Result]END

I'm then using a tableadapter to execute this from my ASP.NET page using the following code,

Protected Sub ExecutePackage()Dim ExecuteAdapterAs New SCC_DAL.RunSSISTableAdapters.SSISRunBuildSCCDWTableAdapter() ExecuteAdapter.SetCommandTimeOut(0)Dim strResultAs String strResult = ExecuteAdapter.Execute() lblResult.Text = strResultEnd Sub

If I remove 'NO_OUTPUT' from my stored procedure and run it the results contain a field named 'output' with all the steps from my package. Then below this is my return value. In my code I can only return the first step of the package results - which tells me nothing useful. I need to be able to return the return value (0-6) in my code.

When I have 'NO_OUTPUT' in my stored procedure and execute it I am left with just the return value. However no value is returned in my code at all although the package does run. I've tried bother RETURN @.ReturnValue and SELECT @.ReturnValue to no avail.

Can someone suggest how I can get the value 0-6 to my code?

Sorted!

Commented out RETURN @.ReturnValue and uncommented the line below it and it works. I had already tried that... bizarre.

Tuesday, March 27, 2012

Executing Oracle Stored Procedure via SQL Server 2000 Linked S

Thanks for the link. I have a stored procedure in Oracle that was created a
long time ago by someone else. Without manipulating the stored proc at all,
I wanted to feed it the required input parameters via SQL Server and let it
do its magic. From what I gather, this is not possible? I must create the
proc within a package in Oracle?
"oj" wrote:

> Here is an old post by Umachandar. See if it helps:
> http://tinyurl.com/7dxrr
> --
> -oj
>
> "marco" <marco@.discussions.microsoft.com> wrote in message
> news:792C4015-008A-420A-B307-EAFC6BAC49EE@.microsoft.com...
>
>Yes. Creating a package wrapper is your ticket to get to oracle proc.
-oj
"marco" <marco@.discussions.microsoft.com> wrote in message
news:4653000F-F545-4044-9876-E113CD14AFE6@.microsoft.com...
> Thanks for the link. I have a stored procedure in Oracle that was created
> a
> long time ago by someone else. Without manipulating the stored proc at
> all,
> I wanted to feed it the required input parameters via SQL Server and let
> it
> do its magic. From what I gather, this is not possible? I must create
> the
> proc within a package in Oracle?
> "oj" wrote:
>

Friday, March 23, 2012

Executing a stored procedure that uses linked server from vb.NET

I can't execute my stored procedure from .NET (I think it might be
because the stored proc has joins in it via linked servers). I get
timeout error from .NET
MyBase.connString ="Integrated Security=SSPI;Persist Security
Info=False;Initial Catalog=DB;Data Source=Server;"
MyBase.selectString = "Exec sp_storedprocedure1 var1,var2,var3"
MyBase.GetDataSet()
The stored procedure takes the 3 arguments and uses joins to 2 other
db-servers that I have access to via linked server connections. (MS SQL
Server)
I can run the stored proc on in QA on my MS SQL with no prob.
Must i open connections to the 2 linked servers from .NET as well?
Glad for any opinions so i dont have to rewrite my sp,
Mikaelbermik wrote:
> I can't execute my stored procedure from .NET (I think it might be
> because the stored proc has joins in it via linked servers). I get
> timeout error from .NET
> MyBase.connString ="Integrated Security=SSPI;Persist Security
> Info=False;Initial Catalog=DB;Data Source=Server;"
>
> MyBase.selectString = "Exec sp_storedprocedure1 var1,var2,var3"
> MyBase.GetDataSet()
>
> The stored procedure takes the 3 arguments and uses joins to 2 other
> db-servers that I have access to via linked server connections. (MS SQL
> Server)
>
> I can run the stored proc on in QA on my MS SQL with no prob.
>
> Must i open connections to the 2 linked servers from .NET as well?
>
> Glad for any opinions so i dont have to rewrite my sp,
>
> Mikael
>
How long does it take to run in QA, and how long is your timeout set for
in .NET?
What are the permissions that you have configured for your linked
servers? Is the user that .NET is connecting with permitted across the
linked servers?|||> How long does it take to run in QA, and how long is your timeout set for
> in .NET?
The stored proc is a monster it takes about 15 min, but I have other
similar sp that work (but without linked server). I used standard time
of 30 but I tried 60 as well with no success, the timeout is only for
gettinga connection right? Not for the whole time for running and
completing the task?
> What are the permissions that you have configured for your linked
> servers? Is the user that .NET is connecting with permitted across the
> linked servers?
I'm using systems current login security context, which is also used
for the linked servers. I will make a simpler sp with a simple select
to 1 of the linked servers to see if it makes a difference, thanks!
/Mikael|||bermik wrote:
>> How long does it take to run in QA, and how long is your timeout set for
>> in .NET?
> The stored proc is a monster it takes about 15 min, but I have other
> similar sp that work (but without linked server). I used standard time
> of 30 but I tried 60 as well with no success, the timeout is only for
> gettinga connection right? Not for the whole time for running and
> completing the task?
>
I'm no .NET programmer, but with typical web apps you have a CONNECTION
timeout and a COMMAND timeout. The defaults, I believe, are 30 seconds.
So, in a nutshell, if your query takes longer than 30 seconds, the web
connection is going to give up and report a timeout.|||> I'm no .NET programmer, but with typical web apps you have a CONNECTION
> timeout and a COMMAND timeout. The defaults, I believe, are 30 seconds.
> So, in a nutshell, if your query takes longer than 30 seconds, the web
> connection is going to give up and report a timeout.
Not a web app, but still makes sense, will check the times. My test
procedure worked out fine so it should have something to do with the
load and not linked server, thanks!
/M|||bermik wrote:
> > I'm no .NET programmer, but with typical web apps you have a CONNECTION
> > timeout and a COMMAND timeout. The defaults, I believe, are 30 seconds.
> > So, in a nutshell, if your query takes longer than 30 seconds, the web
> > connection is going to give up and report a timeout.
> Not a web app, but still makes sense, will check the times. My test
> procedure worked out fine so it should have something to do with the
> load and not linked server, thanks!
> /M
...and timeout it was thanks for your help!
(MyBase.cmdTimeout = 15000)

Executing a stored procedure that uses linked server from vb.NET

bermik wrote:
> I can't execute my stored procedure from .NET (I think it might be
> because the stored proc has joins in it via linked servers). I get
> timeout error from .NET
> MyBase.connString ="Integrated Security=SSPI;Persist Security
> Info=False;Initial Catalog=DB;Data Source=Server;"
>
> MyBase.selectString = "Exec sp_storedprocedure1 var1,var2,var3"
> MyBase.GetDataSet()
>
> The stored procedure takes the 3 arguments and uses joins to 2 other
> db-servers that I have access to via linked server connections. (MS SQL
> Server)
>
> I can run the stored proc on in QA on my MS SQL with no prob.
>
> Must i open connections to the 2 linked servers from .NET as well?
>
> Glad for any opinions so i dont have to rewrite my sp,
>
> Mikael
>
How long does it take to run in QA, and how long is your timeout set for
in .NET?
What are the permissions that you have configured for your linked
servers? Is the user that .NET is connecting with permitted across the
linked servers?
> How long does it take to run in QA, and how long is your timeout set for
> in .NET?
The stored proc is a monster it takes about 15 min, but I have other
similar sp that work (but without linked server). I used standard time
of 30 but I tried 60 as well with no success, the timeout is only for
gettinga connection right? Not for the whole time for running and
completing the task?

> What are the permissions that you have configured for your linked
> servers? Is the user that .NET is connecting with permitted across the
> linked servers?
I'm using systems current login security context, which is also used
for the linked servers. I will make a simpler sp with a simple select
to 1 of the linked servers to see if it makes a difference, thanks!
/Mikael|||bermik wrote:
>
> The stored proc is a monster it takes about 15 min, but I have other
> similar sp that work (but without linked server). I used standard time
> of 30 but I tried 60 as well with no success, the timeout is only for
> gettinga connection right? Not for the whole time for running and
> completing the task?
>
I'm no .NET programmer, but with typical web apps you have a CONNECTION
timeout and a COMMAND timeout. The defaults, I believe, are 30 seconds.
So, in a nutshell, if your query takes longer than 30 seconds, the web
connection is going to give up and report a timeout.|||
> I'm no .NET programmer, but with typical web apps you have a CONNECTION
> timeout and a COMMAND timeout. The defaults, I believe, are 30 seconds.
> So, in a nutshell, if your query takes longer than 30 seconds, the web
> connection is going to give up and report a timeout.
Not a web app, but still makes sense, will check the times. My test
procedure worked out fine so it should have something to do with the
load and not linked server, thanks!
/M|||bermik wrote:
> Not a web app, but still makes sense, will check the times. My test
> procedure worked out fine so it should have something to do with the
> load and not linked server, thanks!
> /M
...and timeout it was thanks for your help!
(MyBase.cmdTimeout = 15000)|||I can't execute my stored procedure from .NET (I think it might be
because the stored proc has joins in it via linked servers). I get
timeout error from .NET
MyBase.connString ="Integrated Security=SSPI;Persist Security
Info=False;Initial Catalog=DB;Data Source=Server;"
MyBase.selectString = "Exec sp_storedprocedure1 var1,var2,var3"
MyBase.GetDataSet()
The stored procedure takes the 3 arguments and uses joins to 2 other
db-servers that I have access to via linked server connections. (MS SQL
Server)
I can run the stored proc on in QA on my MS SQL with no prob.
Must i open connections to the 2 linked servers from .NET as well?
Glad for any opinions so i dont have to rewrite my sp,
Mikael|||bermik wrote:
> I can't execute my stored procedure from .NET (I think it might be
> because the stored proc has joins in it via linked servers). I get
> timeout error from .NET
> MyBase.connString ="Integrated Security=SSPI;Persist Security
> Info=False;Initial Catalog=DB;Data Source=Server;"
>
> MyBase.selectString = "Exec sp_storedprocedure1 var1,var2,var3"
> MyBase.GetDataSet()
>
> The stored procedure takes the 3 arguments and uses joins to 2 other
> db-servers that I have access to via linked server connections. (MS SQL
> Server)
>
> I can run the stored proc on in QA on my MS SQL with no prob.
>
> Must i open connections to the 2 linked servers from .NET as well?
>
> Glad for any opinions so i dont have to rewrite my sp,
>
> Mikael
>
How long does it take to run in QA, and how long is your timeout set for
in .NET?
What are the permissions that you have configured for your linked
servers? Is the user that .NET is connecting with permitted across the
linked servers?|||
> How long does it take to run in QA, and how long is your timeout set for
> in .NET?
The stored proc is a monster it takes about 15 min, but I have other
similar sp that work (but without linked server). I used standard time
of 30 but I tried 60 as well with no success, the timeout is only for
gettinga connection right? Not for the whole time for running and
completing the task?

> What are the permissions that you have configured for your linked
> servers? Is the user that .NET is connecting with permitted across the
> linked servers?
I'm using systems current login security context, which is also used
for the linked servers. I will make a simpler sp with a simple select
to 1 of the linked servers to see if it makes a difference, thanks!
/Mikael|||bermik wrote:
>
> The stored proc is a monster it takes about 15 min, but I have other
> similar sp that work (but without linked server). I used standard time
> of 30 but I tried 60 as well with no success, the timeout is only for
> gettinga connection right? Not for the whole time for running and
> completing the task?
>
I'm no .NET programmer, but with typical web apps you have a CONNECTION
timeout and a COMMAND timeout. The defaults, I believe, are 30 seconds.
So, in a nutshell, if your query takes longer than 30 seconds, the web
connection is going to give up and report a timeout.|||
> I'm no .NET programmer, but with typical web apps you have a CONNECTION
> timeout and a COMMAND timeout. The defaults, I believe, are 30 seconds.
> So, in a nutshell, if your query takes longer than 30 seconds, the web
> connection is going to give up and report a timeout.
Not a web app, but still makes sense, will check the times. My test
procedure worked out fine so it should have something to do with the
load and not linked server, thanks!
/M

Executing a stored proc on another server from a Scheduled task

Ok, I thought this one would be easy.

I have a stored proc: master.dbo.restore_database_foo

This is on database server B.

Database server A backs up database foo on a daily basis as a scheduled
task.

What I wanted to do was, at the end of the scheduled task is then call the
stored proc on B and restore the database.

If I go into Query Analyzer and log into database A, then exec
b.master.dbo.restore_database_foo works.

But if I take the same command and make it part of the scheduled task it
fails.

Error is:

OLE DB provider 'SQLOLEDB' reported an error. [SQLSTATE 42000] (Error 7399)
[SQLSTATE 01000] (Error 7312). The step failed.

To me this seems like a permissions issue, but nothing I've tried seems to
have helped.

Suggestions?

--
--
Greg D. Moore
President Green Mountain Software
Personal: http://stratton.greenms.comGreg D. Moore (Strider) (mooregr@.greenms.com) writes:
> I have a stored proc: master.dbo.restore_database_foo
> This is on database server B.
> Database server A backs up database foo on a daily basis as a scheduled
> task.
> What I wanted to do was, at the end of the scheduled task is then call the
> stored proc on B and restore the database.
> If I go into Query Analyzer and log into database A, then exec
> b.master.dbo.restore_database_foo works.
> But if I take the same command and make it part of the scheduled task it
> fails.
> Error is:
> OLE DB provider 'SQLOLEDB' reported an error. [SQLSTATE 42000] (Error
> 7399) [SQLSTATE 01000] (Error 7312). The step failed.
> To me this seems like a permissions issue, but nothing I've tried seems to
> have helped.

SELECT * FROM master..sysmessages where error in (7399, 7312) gives me

"Invalid use of schema and/or catalog for OLE DB provider '%ls'. A four-part
name was supplied, but the provider does not expose the necessary interfaces
to use a catalog and/or schema." and "OLE DB provider '%ls' reported an
error. %ls"

Doesn't tell me a whole lot.

Can't you take the easy way out and make the step a command-line
step that invokes OSQL?

--
Erland Sommarskog, SQL Server MVP, sommar@.algonet.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||"Erland Sommarskog" <sommar@.algonet.se> wrote in message
news:Xns93EAE9E441CB8Yazorman@.127.0.0.1...
> SELECT * FROM master..sysmessages where error in (7399, 7312) gives me
> "Invalid use of schema and/or catalog for OLE DB provider '%ls'. A
four-part
> name was supplied, but the provider does not expose the necessary
interfaces
> to use a catalog and/or schema." and "OLE DB provider '%ls' reported an
> error. %ls"
> Doesn't tell me a whole lot.

Yeah, same here. It seems to be one of those things that SHOULD be easy.
:-)

> Can't you take the easy way out and make the step a command-line
> step that invokes OSQL?

I could, but that just seems to "dirty" :-)

But that may be the way I go if I can't find a cleaner solution.

> --
> Erland Sommarskog, SQL Server MVP, sommar@.algonet.se
> Books Online for SQL Server SP3 at
> http://www.microsoft.com/sql/techin.../2000/books.asp|||"Greg D. Moore \(Strider\)" <mooregr@.greenms.com> wrote in message news:<wM95b.29715$yG2.21729@.twister.nyroc.rr.com>...
> "Erland Sommarskog" <sommar@.algonet.se> wrote in message
> news:Xns93EAE9E441CB8Yazorman@.127.0.0.1...
> > SELECT * FROM master..sysmessages where error in (7399, 7312) gives me
> > "Invalid use of schema and/or catalog for OLE DB provider '%ls'. A
> four-part
> > name was supplied, but the provider does not expose the necessary
> interfaces
> > to use a catalog and/or schema." and "OLE DB provider '%ls' reported an
> > error. %ls"
> > Doesn't tell me a whole lot.
> Yeah, same here. It seems to be one of those things that SHOULD be easy.
> :-)
> > Can't you take the easy way out and make the step a command-line
> > step that invokes OSQL?
> I could, but that just seems to "dirty" :-)
> But that may be the way I go if I can't find a cleaner solution.
>
> > --
> > Erland Sommarskog, SQL Server MVP, sommar@.algonet.se
> > Books Online for SQL Server SP3 at
> > http://www.microsoft.com/sql/techin.../2000/books.asp

If you are restoring database remotely you should give local admin
privileges on target server to the SQLServerAgent from the primary
server. Just executing stored procedure from the Query Analyzer does
not simulate fully your situation. You should assign one Global
Windows-based account to the SQLServerAgent on primary server and give
it local admin privileges on target server instead of using generic
Local System account. If Network Admins are not cooperative you can
create Local Windows accounts with the same name and password on both
servers and add these accounts to both database servers.

Sinisa Catic

Executing a Stored Proc in SMO

Could anyone show me how to execute a stored procedure using SMO. I can easily see how to created one and drop one but I cannot see how to execute one.

Thanks very much.

Smo does not have any method to Execute a StoredProcedure. You can however use the Database.ExecuteNonQuery method to run the TSQL to execute the stored procedure.

Thanks,

Kuntal

Thursday, March 22, 2012

executing a DTS package from within a stored proc.

How do you execute a DTS package from within a stored proc?create proc newprocedurename as
exec xp_cmdshell "DTSRun /S servername /U username /P password /N packagename"|||True and follow information from books online using DTSRUN utility.|||What if I havent got a username /password assigned to the DB?|||Executewith SA privilege or any other account that has DB access.|||Still no joy...this is what im typing.....

execute xp_cmdshell "DTSRun /S sqlserver /U username /P password /N test_dts1"

sql server is the name of the server, test_dts1 the name of the package.

Anything im doing wrong??

Wednesday, March 21, 2012

ExecuteXMLReader fails with valid xml from sql server. Why?

(From a .net class using sqlcommand)
A stored proc that takes 2 input params is firing on the server (i've
checked using sql profiler). The sp in question produces valid xml (i've
checked by creating a sqlxml virutal dir and allowing url queries - the
result is valid in IE and therefore well formed xml)
The stored proc in question is not a single "select X for xml ..." query. It
is made up of fragments
example of results
<root>
<subnode>
select x ... for xml ...
</subnode>
<subnode>
select x ... for xml ...
</subnode>
...
</root>
Why won't ExecuteXmlReader work with the results?
XR = CMD.ExecuteXmlReader()
(where xr is an xml reader)
this line comes back with the error
"Invalid command sent to ExecuteXmlReader. The command must return an Xml
result."
The command is not invalid! I can see it executing on sql. The result is
valid xml.
I have also tried using the sqlxmlcommand but it claimed I was not passing
parameters in (which I was) so I gave up on that.
I am beginning to hate .net
The concept is great but there is too much pain
trying to connect things together...
Any ideas...?
CODE--
Dim StartDate As String =
ArgsDoc.SelectSingleNode("//Parameter[@.name='startDate']/@.value").Value
Dim EndDate As String =
ArgsDoc.SelectSingleNode("//Parameter[@.name='endDate']/@.value").Value
CMD = New SqlCommand
CMD.Connection = CN
Select Case SubType
Case Nothing
CMD.CommandText = "XXXXX"
CMD.CommandType = CommandType.StoredProcedure
Dim Param As New SqlParameter
CN.Open()
Try
Param.ParameterName = "@.start_date" : Param.Value =
StartDate : CMD.Parameters.Add(Param)
Param = New SqlParameter
Param.ParameterName = "@.end_date" : Param.Value =
EndDate : CMD.Parameters.Add(Param)
Catch ex As System.Exception
System.Diagnostics.Debug.WriteLine(ex.Message)
Finally
End Try
Case Else
'do something
End Select
'--
Try
XR = CMD.ExecuteXmlReader() ' * * * * * * LINE THAT FAILS * * *
* * * *
ResultsDoc = New XmlDocument
ResultsDoc.Load(XR)
Catch ex As System.Exception
System.Diagnostics.Debug.WriteLine(ex.Message)
Finally
End Try
END CODE--
In your description, you create a command like this:

> <root>
> <subnode>
> select x ... for xml ...
> </subnode>
> <subnode>
> select x ... for xml ...
> </subnode>
> ...
> </root>
Where did you do such construction? What type of variable or command are you
using?
One easy solution on Yukon is that you can try is store the result in a
"xml" type variable, and then select from it.
For the ExecuteXmlReader() expecting an "XML" typed data back, instead of
any string that looks like "XML".
Thanks.
Xin
"adolf garlic" wrote:

> (From a .net class using sqlcommand)
> A stored proc that takes 2 input params is firing on the server (i've
> checked using sql profiler). The sp in question produces valid xml (i've
> checked by creating a sqlxml virutal dir and allowing url queries - the
> result is valid in IE and therefore well formed xml)
> The stored proc in question is not a single "select X for xml ..." query. It
> is made up of fragments
> example of results
> <root>
> <subnode>
> select x ... for xml ...
> </subnode>
> <subnode>
> select x ... for xml ...
> </subnode>
> ...
> </root>
> Why won't ExecuteXmlReader work with the results?
> XR = CMD.ExecuteXmlReader()
> (where xr is an xml reader)
> this line comes back with the error
> "Invalid command sent to ExecuteXmlReader. The command must return an Xml
> result."
> The command is not invalid! I can see it executing on sql. The result is
> valid xml.
> I have also tried using the sqlxmlcommand but it claimed I was not passing
> parameters in (which I was) so I gave up on that.
> I am beginning to hate .net
> The concept is great but there is too much pain
> trying to connect things together...
> Any ideas...?
>
> CODE--
>
> Dim StartDate As String =
> ArgsDoc.SelectSingleNode("//Parameter[@.name='startDate']/@.value").Value
> Dim EndDate As String =
> ArgsDoc.SelectSingleNode("//Parameter[@.name='endDate']/@.value").Value
> CMD = New SqlCommand
> CMD.Connection = CN
> Select Case SubType
> Case Nothing
> CMD.CommandText = "XXXXX"
> CMD.CommandType = CommandType.StoredProcedure
> Dim Param As New SqlParameter
> CN.Open()
> Try
> Param.ParameterName = "@.start_date" : Param.Value =
> StartDate : CMD.Parameters.Add(Param)
> Param = New SqlParameter
> Param.ParameterName = "@.end_date" : Param.Value =
> EndDate : CMD.Parameters.Add(Param)
> Catch ex As System.Exception
> System.Diagnostics.Debug.WriteLine(ex.Message)
> Finally
> End Try
> Case Else
> 'do something
> End Select
> '--
> Try
> XR = CMD.ExecuteXmlReader() ' * * * * * * LINE THAT FAILS * * *
> * * * *
> ResultsDoc = New XmlDocument
> ResultsDoc.Load(XR)
> Catch ex As System.Exception
> System.Diagnostics.Debug.WriteLine(ex.Message)
> Finally
> End Try
>
> END CODE--

Monday, March 19, 2012

executeBatch fails on stored proc call

I have a stored procedure that is only supposed to insert if the record
does not already exist.
ALTER PROCEDURE [CARTS].[Insert_Store_Item_Price_Data]
@.Store_Item_Price_Change_ID varchar(50),
@.Store_ID char(4),
@.Item_ID char(14),
@.Batch_Number_ID varchar(6),
@.Effective_Start_Date datetime,
@.Price_AMT decimal(8,2),
@.Promotion_Code smallint,
@.State_Name varchar(10),
@.Record_Creation_Timestamp datetime
AS BEGIN
-- insert a record if no duplicate record is found
DECLARE @.ItemCode char(14)
SELECT @.ItemCode=Item_ID
FROM [CARTS].[Store_Item_Price] WITH (NOLOCK)
WHERE Store_ID=@.Store_ID AND
Item_ID=@.Item_ID AND
Batch_Number_ID = @.Batch_Number_ID AND
Price_AMT = @.Price_AMT AND
Promotion_Code = @.Promotion_Code AND
State_NAME = @.State_NAME
IF(@.ItemCode IS NULL)
BEGIN
INSERT INTO [CARTS].[Store_Item_Price]
([Store_Item_Price_Change_ID]
,[Store_ID]
,[Item_ID]
,[Batch_Number_ID]
,[Effective_Start_Date]
,[Price_AMT]
,[Promotion_Code]
,[State_Name]
,[Record_Creation_Timestamp])
VALUES
(@.Store_Item_Price_Change_ID,
@.Store_ID,
@.Item_ID,
@.Batch_Number_ID,
@.Effective_Start_Date,
@.Price_AMT,
@.Promotion_Code,
@.State_Name,
@.Record_Creation_Timestamp);
END
END
Is there an ELSE statement I can add that will return a zero for rows
effected? That way executeBatch will work. Right now, it returns the
following exception:
java.sql.BatchUpdateException: The returned update count was -1. Either
a procedure returned a result set or not every procedure returned an
update count. The driver expects 11 update counts to be returned from
this batch.StevenMartin (stevenmartin@.us.ibm.com) writes:
> I have a stored procedure that is only supposed to insert if the record
> does not already exist.
>...

> Is there an ELSE statement I can add that will return a zero for rows
> effected? That way executeBatch will work. Right now, it returns the
> following exception:
Write the query as:
INSERT tbl (...)
SELECT ....
WHERE NOT EXISTS (SELECT *
FROM tbl
WHERE ...
Note that there is not any FROM clause in the outer SELECT.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx

Execute Stored Procedure Y asynchronously from Stored Proc X using SQL Server 2000

I am calling a stored procedure (say X) and from that stored procedure (i mean X) i want to call another stored procedure (say Y)asynchoronoulsy. Once stored procedure X is completed then i want to return execution to main program. In background, Stored procedure Y will contiue his work. Please let me know how to do that using SQL Server 2000 and ASP.NET 2.

When you say that you want to return from the SQL server execution.Really all of the Execution has to be completed before that Can Happen.When I say all of the Execution I mean both the X and Y[ that is Y and X internally called by Y].Am not sure that why you want the code to be executed this way but try out following list of possible case that can handle the requirement you have.

1. Stored Procedure X

Statement 1

Statement 2

Call to Y

Statement 4

Statement 5

Split the above code to three ... Statement 1 and 2 be in a single procedure . CAll it , once after execution return ...

from the code , again from the call the SP Y async.

sql API now support Async Calls ..hope your are using that ... BeginXXX and EndXXX pairs

|||

My requirement is little bit different man. I want to do lot of work in backgroud.

when i call a stored proc X then it should execute few lines of code and call Stored Proc Y in background. Once stored proc X call stored proc Y then stored proc X should return me result set (i mean execution of X is done) without waiting to get it complete stored Proc Y because it is running in background.

how can we do it? pls suggest me some solution.

You can suggest me solution either in ASP.NET 2.0 OR Sql Server 2000.

|||

Not very sure, but some ppl said it can be down using OLE automation . Could you please check this article?

http://www.databasejournal.com/features/mssql/article.php/10894_3427581_2

Changing Stored Procedure to Submit Code Asynchronously

Now that you understand the initial performance problem with SP "usp_enter_order," let me discuss how I could re-write this SP to submit the slow code asynchronously. First, I will need to create a "new" SP that contains the slow code. The second thing will be to replace the slow code in "usp_enter_order" with some OLE Automation that submits the "new" SP asynchronously. Below is the code for the new SP, I called it "usp_run_slow_code":

Hope my suggestion can help

Monday, March 12, 2012

Execute stored proc on a named instance

I think I'm being a bit thick, but I just cannot figure out the proper syntax to call a stored proc on a SQL named instance I have. I've tried many variations, but here is the basic format of what I'm trying:

EXEC Server\Instance.DB.dbo.usp_fm_proc 1

It seems it doesn't like the \ as I get an error "Incorrect syntax near 'Instance'.

What am I missing here?

Have you created linekd server, try the following:

EXEC [Server\Instance].DB.dbo.usp_fm_proc 1

|||Dooh! That's it, I was overlooking the []. Thanks!

Execute Stored Proc from OLE DB Destination

is is posible to execute a stored proc (with parameters) from an OLE DB Destination ?

reason we are trying this is cos

our current setup is an OLE DB Command doing the first database update and then passing over to an OLE DB Destination that does the second update. There is error handling coming off the OLE DB Command to a Script component that passes to an OLE DB Destination.

we are having a problem getting the error reporting working from the OLE DB Command - the updates work fine - but not getting any updates of the error database when there is an error.

have got the error reporting fine on the OLE DB Destination.

if we can execute the stored proc from the OLE DB Destination, we will then do both updates via one stored procedure executed by the OLE DB Destination.

thx

m

n.b. think the updating of the error logs from the OLE DB Command used to work - but cant get it to work now ?!!!!?

No, you can't. Why not use another OLE DB command?|||

cos we cant get the error logging to work from the OLE DB Command

and we want to know if any records dont make it

m

|||Well, why can't you get error logging to work? Any, ahem, error messages you can provide us with?|||

phil

thx for this

we couldn't get it to work and could not understand why (followed and re-followed all of the instructions)

today

new member on project, new PC, new SQL installation (SP1), works fine ?

so

am uninstalling SQL from my machine and re-installing it (back to what it was - SP1) - and will see

m

Execute stored proc dynamically (stored a variable)

Hi,
Can someone please show me how to execute a stored proc which has been
assigned to a variable. I have a table of stored procedures and I want to
pick out a certain sp, based on a set of criteria, and execute it
dynamically. I'm thinking of setting up a CURSOR to loop through the selecte
d
sp, assign each one to a variable and then execute it but I don't know how
yet.
I would also like to know how to pass a variable of type TABLE to the above
stored proc. This table type variable contains a list of parameters in a for
m
of "key-value" pairs.
Example
DECLARE @.myTable TABLE(
paramName Varchar(100),
paramValue Varchar(100))
INSERT INTO @.myTable(paramName, paramValue)
VALUES ('param1', '123')
DECLARE @.myStoredProc Varchar(100)
DECLARE myCursor CURSOR FOR
SELECT StoredProcName
FROM tableOfStoredProcs
WHERE something = somethingelse
OPEN myCursor
FETCH NEXT FROM myCursor
INTO @.myStoredProc
...
EXEC @.myStoredProc(@.myTable) -- this is what i want to do but syntactically
incorrect.
I'm using SQL Server 2000.
Any suggestion is greatly appreciated.
CalvinCalvin
CREATE PROC myProc
@.parameter1 VARCHAR(...),
@.parameter2 INT
AS
CREATE TABLE #t
(
spnames SYSNAME PRIMARY KEY
)
INSERT INTO #t VALUES ('sp1')
INSERT INTO #t VALUES ('sp2')
INSERT INTO #t VALUES ('sp3')
SELECT 'EXEC '+spnames+' '''+@.parameter1 +''''+','+cast(@.parameter2 as
varchar(10)) FROM #t
"Calvin KD" <CalvinKD@.discussions.microsoft.com> wrote in message
news:93EFAF4B-C947-4A0D-A230-2C8CDE5CD418@.microsoft.com...
> Hi,
> Can someone please show me how to execute a stored proc which has been
> assigned to a variable. I have a table of stored procedures and I want to
> pick out a certain sp, based on a set of criteria, and execute it
> dynamically. I'm thinking of setting up a CURSOR to loop through the
> selected
> sp, assign each one to a variable and then execute it but I don't know how
> yet.
> I would also like to know how to pass a variable of type TABLE to the
> above
> stored proc. This table type variable contains a list of parameters in a
> form
> of "key-value" pairs.
> Example
> DECLARE @.myTable TABLE(
> paramName Varchar(100),
> paramValue Varchar(100))
> INSERT INTO @.myTable(paramName, paramValue)
> VALUES ('param1', '123')
> DECLARE @.myStoredProc Varchar(100)
> DECLARE myCursor CURSOR FOR
> SELECT StoredProcName
> FROM tableOfStoredProcs
> WHERE something = somethingelse
> OPEN myCursor
> FETCH NEXT FROM myCursor
> INTO @.myStoredProc
> ...
> EXEC @.myStoredProc(@.myTable) -- this is what i want to do but
> syntactically
> incorrect.
> I'm using SQL Server 2000.
> Any suggestion is greatly appreciated.
> Calvin|||Thanks so much for your quick response. I also like to pass the parameters t
o
the stored proc in a form of TABLE type variable, as I demo earlier. This is
because it's a lot more flexible this way. Do you know of a way to do this?
Thanks again.
Calvin
"Uri Dimant" wrote:

> Calvin
>
> --
> CREATE PROC myProc
> @.parameter1 VARCHAR(...),
> @.parameter2 INT
> AS
> CREATE TABLE #t
> (
> spnames SYSNAME PRIMARY KEY
> )
> INSERT INTO #t VALUES ('sp1')
> INSERT INTO #t VALUES ('sp2')
> INSERT INTO #t VALUES ('sp3')
> SELECT 'EXEC '+spnames+' '''+@.parameter1 +''''+','+cast(@.parameter2 as
> varchar(10)) FROM #t
>
>
>
> "Calvin KD" <CalvinKD@.discussions.microsoft.com> wrote in message
> news:93EFAF4B-C947-4A0D-A230-2C8CDE5CD418@.microsoft.com...
>
>|||Hi, Calvin
You cannot pass a table variable as a parameter. You should use a
temporary table or a permanent (normal) table instead. If you expect
that this procedure may be called simultaneously by more users, you can
use @.@.SPID to separate parameters of different processes.
For example:
CREATE TABLE Parameters (
SPID smallint,
ParamName varchar(100),
ParamValue sql_variant,
PRIMARY KEY (SPID,ParamName)
)
GO
CREATE PROCEDURE sp1 AS
SELECT ParamValue FROM Parameters
WHERE SPID=@.@.SPID AND ParamName='param1'
GO
CREATE TABLE tableOfStoredProcs (
StoredProcName sysname PRIMARY KEY
)
INSERT INTO tableOfStoredProcs VALUES ('sp1')
GO
INSERT INTO Parameters (SPID, ParamName, ParamValue)
VALUES (@.@.SPID, 'param1', 123)
DECLARE @.myStoredProc Varchar(100)
DECLARE myCursor CURSOR LOCAL READ_ONLY FOR
SELECT StoredProcName FROM tableOfStoredProcs
--WHERE ...
OPEN myCursor
WHILE 1=1 BEGIN
FETCH NEXT FROM myCursor INTO @.myStoredProc
IF @.@.FETCH_STATUS<>0 BREAK
EXEC @.myStoredProc
END
CLOSE myCursor
DEALLOCATE myCursor
DELETE Parameters WHERE SPID=@.@.SPID
GO
This usage of EXEC, without parentheses (i.e. "EXEC @.ProcedureName"),
is less vulnerable to SQL Injection attacks than using "EXEC
(@.SQLString)".
Razvan|||Calvin
Read those articles
http://www.sommarskog.se/dynamic_sql.html
http://www.sommarskog.se/arrays-in-sql.html
"Calvin KD" <CalvinKD@.discussions.microsoft.com> wrote in message
news:F367EEC4-4B38-4F21-836D-2ADBF2910C9B@.microsoft.com...
> Thanks so much for your quick response. I also like to pass the parameters
> to
> the stored proc in a form of TABLE type variable, as I demo earlier. This
> is
> because it's a lot more flexible this way. Do you know of a way to do
> this?
> Thanks again.
> Calvin
> "Uri Dimant" wrote:
>|||Thank you Razvan for your quick response. That's pretty much what i was
after. My original idea was to pass in a "data structure" as a parameter to
the stored procs and then each stored proc picks out what it needs for
processing.
Anyway, it's a good start.
Thanks.
Calvin
"Razvan Socol" wrote:

> Hi, Calvin
> You cannot pass a table variable as a parameter. You should use a
> temporary table or a permanent (normal) table instead. If you expect
> that this procedure may be called simultaneously by more users, you can
> use @.@.SPID to separate parameters of different processes.
> For example:
> CREATE TABLE Parameters (
> SPID smallint,
> ParamName varchar(100),
> ParamValue sql_variant,
> PRIMARY KEY (SPID,ParamName)
> )
> GO
> CREATE PROCEDURE sp1 AS
> SELECT ParamValue FROM Parameters
> WHERE SPID=@.@.SPID AND ParamName='param1'
> GO
> CREATE TABLE tableOfStoredProcs (
> StoredProcName sysname PRIMARY KEY
> )
> INSERT INTO tableOfStoredProcs VALUES ('sp1')
> GO
> INSERT INTO Parameters (SPID, ParamName, ParamValue)
> VALUES (@.@.SPID, 'param1', 123)
> DECLARE @.myStoredProc Varchar(100)
> DECLARE myCursor CURSOR LOCAL READ_ONLY FOR
> SELECT StoredProcName FROM tableOfStoredProcs
> --WHERE ...
> OPEN myCursor
> WHILE 1=1 BEGIN
> FETCH NEXT FROM myCursor INTO @.myStoredProc
> IF @.@.FETCH_STATUS<>0 BREAK
> EXEC @.myStoredProc
> END
> CLOSE myCursor
> DEALLOCATE myCursor
> DELETE Parameters WHERE SPID=@.@.SPID
> GO
> This usage of EXEC, without parentheses (i.e. "EXEC @.ProcedureName"),
> is less vulnerable to SQL Injection attacks than using "EXEC
> (@.SQLString)".
> Razvan
>|||Calvin KD (CalvinKD@.discussions.microsoft.com) writes:
> Thanks so much for your quick response. I also like to pass the
> parameters to the stored proc in a form of TABLE type variable, as I
> demo earlier. This is because it's a lot more flexible this way. Do you
> know of a way to do this?
Uri's suggestion is far too complex. Just say:
EXEC @.spname @.par1, @.par2, @.par3
Uri suggested some aritcles on my web site, but not the one which appears
to be the most pertinent to your problem,
http://www.sommarskog.se/share_data.html. This article discusses techniques
to share data between stored procedures. Unforunately, table variables
cannot do that task.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||Thank you all for your responses. I have certainly learnt a few new things.
As for my quest, I think I'll just have to pass the same number of parameter
s
to each stored proc (even though some aren't used) unless we can come up wit
h
a better solution.
The problem we're facing is that because we have a long list of stored procs
(which will expand over the years) that we want to exec., and exactly which
stored proc will be exec. depends on certain criteria for each year. Some
will be "On" in one year and may be "Off" the next.
Example:
tblStoredProcs
=========
StoredProcID
StoredProcName
Year
Active
Anyway, if anyone has an idea, please let me know. All suggestions are
greatly welcomed.
Cheers,
Calvin
"Erland Sommarskog" wrote:

> Calvin KD (CalvinKD@.discussions.microsoft.com) writes:
> Uri's suggestion is far too complex. Just say:
> EXEC @.spname @.par1, @.par2, @.par3
> Uri suggested some aritcles on my web site, but not the one which appears
> to be the most pertinent to your problem,
> http://www.sommarskog.se/share_data.html. This article discusses technique
s
> to share data between stored procedures. Unforunately, table variables
> cannot do that task.
>
> --
> Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
> Books Online for SQL Server 2005 at
> http://www.microsoft.com/technet/pr...oads/books.mspx
> Books Online for SQL Server 2000 at
> http://www.microsoft.com/sql/prodin...ions/books.mspx
>|||Calvin KD (CalvinKD@.discussions.microsoft.com) writes:
> Thank you all for your responses. I have certainly learnt a few new
> things. As for my quest, I think I'll just have to pass the same number
> of parameters to each stored proc (even though some aren't used) unless
> we can come up with a better solution.
It sounds like an excellent solution to me! After all, that is as
close to the implemention of a the O-O concept of a virtual class you
can come in T-SQL.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx

Execute Stored Proc and then return a value

ok I have a stored procedure in my MS-SQL Server database.
It looks something like this....

CREATE PROCEDURE updatePCPartsList
(
@.Description varchar(255),
@.ManCode varchar(255),
@.ProdCode varchar(255),
@.Price decimal(6,2),
@.Comments varchar(255)
)
AS

declare @.IDFound bigint
declare @.LastChangedDate datetime

select @.LastChangedDate = GetDate()
select @.IDFound = PK_ID from PCPartsList where ProdCode = @.ProdCode

if @.IDFound > 0
begin
update PCPartsList set Description = @.Description, ManCode = @.ManCode, ProdCode = @.ProdCode, Price = @.Price, Comments = @.Comments, LastChanged = @.LastChangedDate where PK_ID = @.IDFound
end
else
insert into PCPartsList (Description, ManCode, ProdCode, Price, Comments, LastChanged) values(@.Description, @.ManCode, @.ProdCode, @.Price, @.Comments, @.LastChangedDate)
GO

It executes fine so I know i've done that much right...
But what i'd like to know is how I can then return a value - specifically @.LastDateChanged variable

I think this is a case of i've done the hard part but i'm stuck on the simple part - but i'm very slowly dragging my way through learning SQL.
Someone help?You can add an extra parameter to the call, which you can use as an output variable.

Try the following:

CREATE PROCEDURE updatePCPartsList
(
@.Description varchar(255),
@.ManCode varchar(255),
@.ProdCode varchar(255),
@.Price decimal(6,2),
@.Comments varchar(255),
@.LastChangedDate datetime output
)
AS
declare @.IDFound bigint
select @.LastChangedDate = GetDate()
select @.IDFound = PK_ID from PCPartsList where ProdCode = @.ProdCode
if @.IDFound > 0
begin
update PCPartsList set Description = @.Description, ManCode = @.ManCode, ProdCode = @.ProdCode, Price = @.Price, Comments = @.Comments, LastChanged = @.LastChangedDate where PK_ID = @.IDFound
end
else
insert into PCPartsList (Description, ManCode, ProdCode, Price, Comments, LastChanged) values(@.Description, @.ManCode, @.ProdCode, @.Price, @.Comments, @.LastChangedDate)
GO

When you call the proc you'll need to capture the output to a variable of your choice so do something like:

DECLARE @.LCDate datetime
EXEC updatePCPartsList
@.Description='Dummy Item',
@.ManCode='12121',
@.ProdCode='54321',
@.Price=123,
@.Comments='blah blah',
@.LastChangedDate=@.LCDate OUTPUT

then @.LCDate should contain the result.|||Ok - I kinda see what your doing but i'm not sure if it's what i'm looking for....

First let me explain my situation a bit more....
I'm writing an application (specifically an excel spreadsheet using vba) in which I need to execuite that stored procedure and then return the @.LastChangedDate value to a variable in my VBA.

Can I use your example still?
Would your additional bit of SQL be a second Stored Proc? And would I call that - not my first proc?|||Ah, I assumed you were wanting the result in a SQL local variable, not passed to Excel. I doubt you'd be able to use that modification for your needs

Sadly, I'm no VBA wizard but I'd assume you need to alter your original stored proc to have a "SELECT @.LastChangedDate" at the end so it prints the output you want into the resultset.

Assuming you've used the SQLExecuteQuery command to run the query you should be able to use SQLRetrieve to get the resultset and extract the value from there.

SQLRetrieve allows you to specify an Excel cell range to put the results in and a max rows/cols value (which you'd have set to 1).

The VBA help in Excel has a nice reference for SQLExecuteQuery and SQLRetrieve, with a few examples that may help.

Friday, March 9, 2012

Execute SQL Task speed

I've created a SSIS package, in a sql 2005 instance, that uses an Execute SQL Task" to call a stored proc as its last step. When run from BIDS, the last step takes about 2 to 3 minutes, consistently. When I run the exact same query from Management Studio (either via exec <spname> or by copying the sp's t-sql code into a query window) it consistently takes about 1 minute. I've run sevral test and these number are quite reproducible.

Any ideas to account for the "slowness" of the Execute SQL Task?

TIA,

Barkingdog

Hi, are you running your package in debug mode?

Try run the package without Visual Studio.

John Bocachica - Colombia

www.iquos-bi.com

|||

The dropdown box at the top of BIDs says "Development"

Here is what I have found. My package runs three control tasks. When I run all three, the Exec SQL tasks takes about 2 minutes to run but when I execute ONLY the Exec SQL task that task runs in about 1 minute!

I saved the package (in BIDS) to a .dtsx file and ran it. The whole process took about 2.5 miniutes which tells me that the Exec SQL task still took about 2 minutes.

barkingdog

|||

What are the other tasks doing? Do they use the same database connection? Are there transactions involved?

|||

The first task truncates a table called Contact. The second task imports a CSV file into a table (uses a SQL Server Destination. Does a straight copy of the data; no transformations. The file imported is on the sql 2005 server and database I'm importing into). The third task (Exec SQL Task) applies various UPDATE statements to the table populated in step 2. Steps 2 and 3 use the same sql connection.

II don't know how to tell if all the tasks belong to the same transaction. I set up three control flows in the same pane but they are not contained in any container object, if that helps at all.)

TIA,

Barkingdog

Execute SQL Task hangs...

Hi,

I'm having a problem with one 'Execute SQL Task' calling a stored proc...

The problem is that once the stored proc has finished executing after 10 mins (I know it has thanks to an audit log table entry ), the SSIS task carries on hanging for another 20mins before it gets the task execution result and moves to the following task.

I tried:

- adding/removing a return statement at the end of the stored proc. It doesn't solve the problem

- running the package without debugging and outside visual studio, and I'm still getting the same problem. so it's nothing to do with the debugger...

- tried various settings for the transaction and isolation settings... not getting any better

- changed the stored proc so that it processes less data. Execution time goes down to a couple of minutes and the SSIS tasks only hangs for 2 mins... better but not really helping...

Any clues? I'm new to SSIS so I must have certainly missed something!

Thanks.

Have you used SQL Server profiler to check if the SP has actually finished? I never have seen that problem before and I cannot think it is a problem in SSIS.|||Check for blocking, plenty of info in Books Online. I'm old school so try sp_who2 as start.|||

sp_who2 was another thing I tried... there was no runnable process, no lock etc..

anyway, I finally managed to sort this out... I changed the connection type from OLE DB to ADO.NET and it did the trick...

I have to say it's rather puzzling... I did check the stored proc in case there was something unusual... nocount is set to on, there is not print statement, no select statement, just one return at the end of the stored proc...

when running in visual studio, the debugger process runs at full cpu but doesn't do anything apart from eating more and more memory...

anyway, it's sorted for the time being...

Thanks for your suggestions.

Sunday, February 26, 2012

execute proc on stopping mssql server

How execute extended proc on stopping ms sql server (it mean before
stoping).
Is it possible to handle this?
Or is in system proc a'la sp_on_stop?

ThxIndrek Mgi (mkkk@.hotmail.com) writes:
> How execute extended proc on stopping ms sql server (it mean before
> stoping).
> Is it possible to handle this?
> Or is in system proc a'la sp_on_stop?

KILL on the spid in question is the only way I can think of. Short of
rebooting the server.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||Try this,

--Email when database is started

CREATE procedure email

as

exec sp_sendSMTPmail 'test@.test.com.au', 'Database Rebooted',
@.cc='', @.BCC = '',
@.Importance=1,
@.Attachments='', @.HTMLFormat = 0,@.From =
'test@.test.com.au'

GO
exec sp_procoption N'email', N'startup', N'true'
GO

Thanks,

"Indrek Mgi" <mkkk@.hotmail.com> wrote in message
news:4215cb43_2@.news.estpak.ee...
> How execute extended proc on stopping ms sql server (it mean before
> stoping).
> Is it possible to handle this?
> Or is in system proc a'la sp_on_stop?
> Thx

Sunday, February 19, 2012

Execute Multiple SQL statements in Stored Proc

Hi, I have a table containing SQl statements. I need to extract the statements and execute them through stored procedure(have any better ideas?)

Table Test

Id Description

1 Insert into test(Id,Name) Values (1,'Ron')
2 Update Test Set Name = 'Robert' where Id = 1
3 Delete from Test where Id = 1

In my stored procedure, i want to execute the above statements in the order they were inserted into the table. Can Someone shed some light on how to execute multiple sql statements in a stored procedure. Thanks

ReoI hope this will help u.
--Insert statement
--insert into Test values(1, 'Insert into test(Id,Name) Values (1,''Ron'')')

declare @.sql varchar(8000)
select @.sql=Description from Test where Id=1
--print @.sql
exec (@.sql)|||Sounds like homework. What have you tried?

Friday, February 17, 2012

Execute MDX from SQL Proc

------------------------

Can someone shed some light? I have searched hi and low for an answer to my dilemma. I have an mdx query that works fine in my olap environment but when I try to run the same query from sql 2000, one of my calculations comes back as a long int and includes (E-02) at the end. Can you please review my store procedure and provide some insight?

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

ALTER PROCEDURE GetWeeklyTrendData

@.Level int,
@.year int,
@.week int,
@.PrintMDX int = 0

AS

SET NOCOUNT ON

DECLARE @.MDX varchar(4000),
@.CubeQuery varchar(4500), @.Leaf int, @.Tier int

BEGIN
SET @.MDX = '''
WITH
MEMBER [Measures].[OrgName] As ''''[GL].CurrentMember.Name''''
MEMBER [Measures].[LevelSKey] As ''''[GL].CurrentMember.Properties("Key")''''
MEMBER [Measures].[OrgType] As ''''Iif(IsLeaf([GL].CurrentMember), 1, 0)''''
MEMBER Measures.Lookp AS '''' LookupCube("cubeName", "(Measures.Customers, " + [GL].CurrentMember.UniqueName + "," + [Week].CurrentMember.UniqueName + ")" )''''

MEMBER Measures.Trend AS '''' Measures.Customers / LookupCube("cubeName", "(Measures.Customers, " + [GL].CurrentMember.UniqueName + "," + [Week].CurrentMember.UniqueName + ")" )''''
, SOLVE_ORDER = 1, FORMAT_STRING = ''''Percent''''

SELECT
{
CrossJoin
(
{ [Week].[' + CAST(@.year AS VARCHAR) + '].[Week ' + CAST(@.week AS VARCHAR)+ '].Lag(12) : [Week].[' + CAST(@.year AS VARCHAR) + '].[Week ' + CAST(@.week AS VARCHAR) + '] },
{ Measures.OrgName, Measures.LevelSKey, Measures.OrgType, Measures.Customers, Measures.Lookp , Measures.Trend
}
) } ON COLUMNS,
NON EMPTY
{ [GL].&[' + CAST (@.Level AS VARCHAR) + '].Children } ON Rows
FROM [cubeName]
WHERE

( [Monthly Income].[All Monthly Income].[Y],[Contact Events].[All Contact Events].[Y],
[Other Financial].[All Other Financial].[Y],[Bankers Notes].[All Bankers Notes].[Y],
[Employer Name].[All Employer Name].[Y] )
'''
END
SELECT @.CubeQuery =
'
SELECT *
FROM OPENQUERY(ReportDBMart, ' + @.MDX + ')'
IF @.PrintMDX = 1
PRINT 'MDX: ' + @.MDX

EXEC(@.CubeQuery)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

The following is the value that I get back.
9.4993517502742597E-2 and is derived from Measures.Trend.

My guess is that it doesnt recognize FORMAT_STRING = ''''Percent'''' or its trying to return a numeric value inside a varchar. Any thoughts?You've got a real number expressed in scientific notation. The 9.4993517502742597E-2 is exactly the same thing as 0.094993517502742597

-PatP

Execute Function

hi all,

say for eg i have a function and proc named as fun_sample and proc_sample respectivley.

why do we specify "dbo.fun_sample" for executing the function, whereas only "proc_sample" is enought for executing the proc?

For scalar function:

select dbo.fun_sample()

or

declare @.v int

set @.v = dbo.fun_sample()

For table-value function:

select * from dbo.fun_sample()

|||sorry, u have not got my question.

my doubt is why we are specifying the ownername for executing a function?|||"dbo." isn't owner name, it's schema. If you use function without schema name, SQL Server think that it's system function. For stored procedures "sp_" prefix is a reason to resolving as system stored procedure.|||

firstly its a schema name or owner name, depending on the version of sql server being used...owner for 2000 and schema for 2005

for the main question...why dbo. for a function... i guess its just a syntax thing ...and it does saves time for the server... so maybe i'll use it evn if its not mandatory.... use it for sps as well....