Showing posts with label procedures. Show all posts
Showing posts with label procedures. Show all posts

Thursday, March 29, 2012

Can I have Exec(...) statements within a transcation ?

Is the following T-SQL correct, in which I am trying to make sure that th effect of 3 stored procedures gets reversed in case of an error ? I know if in place of stored procedures I had action queries like 'ActionQry1', 'ActionQry2' and 'ActionQry3' then the transaction logic would work. But will it work even if exec(...) statements are there in the transaction ? Each stored procedure is made up of an action query.

begin tran
exec("storeprocedure1('2')")
if @.@.error=0
begin
exec("storeprocedure2")
if @.@.error=0
begin
exec("storeprocedure3(122)")
if @.error=0
commit tran
else
rollback tran
end
else
rollback tran
end
else
rollback transure, exec statements will work,
but your syntax is not correct, it should be like this:


begin tran
statement1

if (@.@.error <> 0)
begin
rollback tran
return
end

statement2
if (@.@.error <> 0)
begin
rollback tran
return
end

commit tran

Tuesday, March 27, 2012

Can I group stored procedures some way

Hi folks!
I'm working on a report that requires about 20 SPs to retrieve data.
My code would be better if I could somehow create some object
(package?) that would have all my 20 SPs in it.
This way if I have 100 reports it will be easy to manage the SPs in the
database.
I thought I read several years ago there was a way to do this. Is there
still a way?
Thanks in advance.Bob wrote:
> Hi folks!
> I'm working on a report that requires about 20 SPs to retrieve data.
> My code would be better if I could somehow create some object
> (package?) that would have all my 20 SPs in it.
> This way if I have 100 reports it will be easy to manage the SPs in
> the database.
> I thought I read several years ago there was a way to do this. Is
> there still a way?
> Thanks in advance.
I'm about you're actually trying to do here. Are you talking
about packaging your procedures in order to create them on another
database? Can you give an example of what you need?
David Gugick
Imceda Software
www.imceda.com|||"Bob" <Go1369@.Yahoo.Com> wrote in message
news:1109359684.432319.268490@.l41g2000cwc.googlegroups.com...
> Hi folks!
> I'm working on a report that requires about 20 SPs to retrieve data.
> My code would be better if I could somehow create some object
> (package?) that would have all my 20 SPs in it.
> This way if I have 100 reports it will be easy to manage the SPs in the
> database.
> I thought I read several years ago there was a way to do this. Is there
> still a way?
>
Are you refering to the stored procedure number?
CREATE PROC [ EDURE ] procedure_name [ ; number ]
. . .
;number
Is an optional integer used to group procedures of the same name so they can
be dropped together with a single DROP PROCEDURE statement. For example, the
procedures used with an application called orders may be named orderproc;1,
orderproc;2, and so on. The statement DROP PROCEDURE orderproc drops the
entire group. If the name contains delimited identifiers, the number should
not be included as part of the identifier; use the appropriate delimiter
around procedure_name only.
This can be used to group procedures, but it's an old and rarely used
feature, and you run the risk of confusing people. I would probably just
use a common name prefix to sort and identify the related procedures.
David

Monday, March 19, 2012

Can I achieve WITH(NOLOCK) on all joins in a stored procedure with a single command?

I have a number of reporting stored procedures that purely list
records and make no changes to the data. I have noticed that some of
these SPs are causing blocks so I am adding the WITH(NOLOCK) hint. For
a simple example :-
Select * from table1 WITH(NOLOCK)
INNER JOIN table2 WITH(NOLOCK) ON table1.UID=table2.UID
INNER JOIN table3 WITH(NOLOCK) ON table1.AnotherID=table3.AnotherID
LEFT OUTER JOIN table4 WITH(NOLOCK) ON table3.ThisID=table4.ThisID
There lots of these and many of them have lots of joins so I'm looking
for a way to apply WITH(NOLOCK) to the whole procedure and save myself
the time it takes to add the hint to each table/join. I know that it
is possible to use SET DEADLOCK_PRIORITY LOW, forcing the procedure to
volunteer as the deadlock victim, but this isn't suitable as I need
the procedure to return it's records.
Does anybody have a suggestion or am I looking ata couple of days of
ctrl-v'ing WITH(NOLOCK) everywhere?
Thanks,
LiamHow about below?
SET STRANSACTION ISOLATION LEVEL READ UNCOMMITTED
--
Tibor Karaszi, SQL Server MVP
Archive at: http://groups.google.com/groups?oi=djq&as_ugroup=microsoft.public.sqlserver
"Liam Weston" <liam_weston@.hotmail.com> wrote in message
news:5f9a8c3b.0310310227.436b158b@.posting.google.com...
> I have a number of reporting stored procedures that purely list
> records and make no changes to the data. I have noticed that some of
> these SPs are causing blocks so I am adding the WITH(NOLOCK) hint. For
> a simple example :-
> Select * from table1 WITH(NOLOCK)
> INNER JOIN table2 WITH(NOLOCK) ON table1.UID=table2.UID
> INNER JOIN table3 WITH(NOLOCK) ON table1.AnotherID=table3.AnotherID
> LEFT OUTER JOIN table4 WITH(NOLOCK) ON table3.ThisID=table4.ThisID
> There lots of these and many of them have lots of joins so I'm looking
> for a way to apply WITH(NOLOCK) to the whole procedure and save myself
> the time it takes to add the hint to each table/join. I know that it
> is possible to use SET DEADLOCK_PRIORITY LOW, forcing the procedure to
> volunteer as the deadlock victim, but this isn't suitable as I need
> the procedure to return it's records.
> Does anybody have a suggestion or am I looking ata couple of days of
> ctrl-v'ing WITH(NOLOCK) everywhere?
> Thanks,
> Liam|||Thanks, that's just what I was looking for.
Liam
"Tibor Karaszi" <tibor.please_reply_to_public_forum.karaszi@.cornerstone.se> wrote in message news:<uvCEm35nDHA.2312@.TK2MSFTNGP12.phx.gbl>...
> How about below?
> SET STRANSACTION ISOLATION LEVEL READ UNCOMMITTED
> --
> Tibor Karaszi, SQL Server MVP
> Archive at: http://groups.google.com/groups?oi=djq&as_ugroup=microsoft.public.sqlserver
>
> "Liam Weston" <liam_weston@.hotmail.com> wrote in message
> news:5f9a8c3b.0310310227.436b158b@.posting.google.com...
> > I have a number of reporting stored procedures that purely list
> > records and make no changes to the data. I have noticed that some of
> > these SPs are causing blocks so I am adding the WITH(NOLOCK) hint. For
> > a simple example :-
> >
> > Select * from table1 WITH(NOLOCK)
> > INNER JOIN table2 WITH(NOLOCK) ON table1.UID=table2.UID
> > INNER JOIN table3 WITH(NOLOCK) ON table1.AnotherID=table3.AnotherID
> > LEFT OUTER JOIN table4 WITH(NOLOCK) ON table3.ThisID=table4.ThisID
> >
> > There lots of these and many of them have lots of joins so I'm looking
> > for a way to apply WITH(NOLOCK) to the whole procedure and save myself
> > the time it takes to add the hint to each table/join. I know that it
> > is possible to use SET DEADLOCK_PRIORITY LOW, forcing the procedure to
> > volunteer as the deadlock victim, but this isn't suitable as I need
> > the procedure to return it's records.
> >
> > Does anybody have a suggestion or am I looking ata couple of days of
> > ctrl-v'ing WITH(NOLOCK) everywhere?
> >
> > Thanks,
> >
> > Liam

Thursday, March 8, 2012

can datasets access sql server schemas

I have a database in sql server 2005. I have a schema called A. (Create schema A). THen I have several tables and procedures in that schema. Yet, when I update my reports to use the new tables with the schema name (select blah from A.table), I receive an error on the site that says "invalid object name 'A.table'"

How do I get RS to understand my schema? I'm using a sql server account as credentials for my data source.

Thanks,
-LoriUser error. I was tired. My datasource was not being deployed, and the tables did not exist in the old datasource. Once I updated the report/datasource and re-deployed, I could see the tables.

Wednesday, March 7, 2012

Can backups be done via stored procedures?

That's my question.
Thanks,
Tom
To add on to Tibor, This procedure will Backup Master, MSDB and all the User
databases. This script will create the unique Backup
files names, this will ensure that old backup sets were not overwritten.
Script
CREATE PROCEDURE BACKUP_SP AS
BEGIN
SET NOCOUNT ON
DECLARE @.NAME VARCHAR(100),
DECLARE @.DBNAME VARCHAR(100)
DECLARE BACKUP_CUR CURSOR FOR
SELECT name FROM master..Sysdatabases where name not in
('model','pubs','tempdb','northwind')
OPEN BACKUP_CUR
FETCH NEXT FROM BACKUP_CUR INTO @.DBNAME
WHILE @.@.FETCH_STATUS=0
BEGIN
SELECT @.NAME='C:\backup\'+@.DBNAME+'_'+ltrim (rtrim (convert
(char,getdate(),105)))+'Dump.bak'
BACKUP DATABASE @.DBNAME TO DISK = @.NAME WITH INIT , NOUNLOAD , NAME
= @.DBNAME, NOSKIP, STATS = 10, NOFORMAT
FETCH NEXT FROM BACKUP_CUR INTO @.DBNAME
END
CLOSE BACKUP_CUR
DEALLOCATE BACKUP_CUR
END
How to Execute:
EXEC BACKUP_SP
This will backup all the databases to the SQLBACKUP folder in BACKUPSERVER.
Thanks
Hari
"Tom Glasser" <TomGlasser@.discussions.microsoft.com> wrote in message
news:4125EFFF-9C29-491D-87F0-BD29969F0EF9@.microsoft.com...
> That's my question.
> Thanks,
> Tom

Friday, February 24, 2012

Can an adapter handle a stored procedures?!

Can someone please help on this issue and tell me how to amend this code:
<WebMethod()> _
Public Function GetRecord(ByVal anyname As String) As DataSet
Dim adapter As New SqlDataAdapter
Dim result As New DataSet
adapter.SelectCommand.Connection = Conn
adapter.SelectCommand.CommandType = CommandType.StoredProcedure
adapter.SelectCommand.CommandText = "GetSingleName"
adapter.SelectCommand.Parameters.Add("@.myname", SqlDbType.VarChar)
adapter.SelectCommand.Parameters("@.myname").Direction =
ParameterDirection.Input
adapter.SelectCommand.Parameters("@.myname").Value = anyname
adapter.Fill(result, "nabData")
Return result
This code is supposed to resturn dataset filled by an adapter that uses a
stored procedure called "GetSingleName". The Database table is "nabData". Th
e
connection is established through the GUI and is named Conn.
Many thanks in advance.Nab wrote:
> Can someone please help on this issue and tell me how to amend this code:
> <WebMethod()> _
> Public Function GetRecord(ByVal anyname As String) As DataSet
> Dim adapter As New SqlDataAdapter
> Dim result As New DataSet
> adapter.SelectCommand.Connection = Conn
> adapter.SelectCommand.CommandType = CommandType.StoredProcedure
> adapter.SelectCommand.CommandText = "GetSingleName"
> adapter.SelectCommand.Parameters.Add("@.myname", SqlDbType.VarChar)
> adapter.SelectCommand.Parameters("@.myname").Direction =
> ParameterDirection.Input
> adapter.SelectCommand.Parameters("@.myname").Value = anyname
> adapter.Fill(result, "nabData")
> Return result
> This code is supposed to resturn dataset filled by an adapter that uses a
> stored procedure called "GetSingleName". The Database table is "nabData".
The
> connection is established through the GUI and is named Conn.
--BEGIN PGP SIGNED MESSAGE--
Hash: SHA1
This is a question, better answered in a VB.NET newsgroup.
Wrist slapping done...
An example in C# (untested):
// create connection
String connString = "Data Source=(local);Integrated security=SSPI;" +
"Initial Catalog=Northwind;";
SqlConnection conn = new SqlConnection(connString);
// create a Command object based on a stored procedure
String selectSql = "MyStoredProcedure";
SqlCommand selectCmd = new SqlCommand(selectSql, conn);
selectCmd.CommandType = CommandType.StoredProcedure;
// create and set the parameter for the stored procedure
selectCmd.Parameters.Add("@.CustomerID", SqlDbType.NChar, 5);
selectCmd.Parameters["@.CustomerID"].Value = "VINET";
SqlDataAdapter da = new SqlDataAdapter(selecteCmd);
// create a new DataSet to receive the data
DataSet ds = new DataSet();
// read the data from stored procedure & load it into the DataSet
da.Fill(ds);
A good ADO.NET reference is _ADO.NET In a Nutshell_ (pub: O'Reilly).
MGFoster:::mgf00 <at> earthlink <decimal-point> net
Oakland, CA (USA)
--BEGIN PGP SIGNATURE--
Version: PGP for Personal Privacy 5.0
Charset: noconv
iQA/ AwUBQhjdeoechKqOuFEgEQIg9QCgxmdNXsVA6uhC
wOZGYdYzwpAW+E4An2q8
rXQKtPYE2AAus6bK5zAe4beW
=IcRz
--END PGP SIGNATURE--

Can a user be granted Read Only privileges for stored procedures

Can a user be granted the ability to create stored procedures with read only capabilities? I wouldn't mind be able to UPDATE but simply need to read only.
ddaveI don't understand...

You GRANT EXECUT to sprocs...

Do you mean to the underlying tables?

Personally...

In our Prodction environment, we hand the scripts over to the prod dba...

the run the script and it gets created as dbo...

users are granted execute to the sprocs...|||Hi Brett,

In one of the companies I am working for I am requesting the ability to create stored procedures. The data is extremely sensitive however. It is for a financial company where access to this data would allow someone like myself to alter data, ie wire myself money. I don't want that to be a concern of course so I was wondering if I could run stored procedures with the ability to read but not alter the data. Is there such a thing? Thanks.

ddave|||Yes,

But it's at the table

either

GRANT SELECT ON dbTable TO yourID

Or have the dba put you in a role...

That's what I'd do...
set up a role...call readonly or whatever..

GRANT SELECT on all tables

SELECT 'GRANT SELECT ON ' + TABLE_NAME + 'TO readonly'
FROM INFORMATION_SCHEMA.TABLES

And just put your id in that role...

makes managing alot easier....|||One slight problem, though. If you have a table that you can only read, you can still execute procedures that update/insert/delete that table. The select permissions that you are granted only really extend to the actions that you yourself are running (outside stored procedures).

This of course only applies to objects with an unbroken chain of ownership. If you put yourself in a role that has been denied update, delete, insert on the specific tables, then you could create procedures in your own schema that do almost anything. But you yourself (and anyone running them) would be limited by their own permissions on the underlying tables. This is not a fun place to be for a livinig system that will have various coders running around tieing their applications, reports, and what-not into various bits of code that were left lying around.|||Well just before the database crashed...AGAIN...

I was going to say I agree...

Don't you have a dev environment?

playing in production is not a good thing...

oops

Now what did I do with that backup?|||Does the db_datareader (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_sp_da-di_9nla.asp) role fit the bill?

-PatP|||No, I don't have a dev environment. How do you get one? The company I work for is huge but this is one small department granting me the ability to access this data. I know that there is a lot for them and myself to learn.

ddave|||Keep in mind that (at least for the most part) the permissions used by a stored procedure are the permissions of the user that creates the stored procedure. There are a few exceptions, but very, very few. The procedure's EXECUTE permission is the only permission that matters to the user that runs the stored procedure.

This allows a "super user" like dbo to create a procedure that can do almost anything, then give other "underprivledged" users permission to execute that procedure.

-PatP|||Do you have a dba?

If I were you, I'd make SURE that I didn't get blamed for ANYTHING...

and that means staying out of production, and be isolated in another environment...

What do you have to do?|||So Pat,

What you're telling me is that since my contact in this other department has the ability to EXECUTE stored procedures, it's either feast or famine. I will either be able to run sprocs AND perform DML commands or not based on whether he GRANTs me these permissions or not. Is this correct? Thanks.

ddave|||Sorry, but SQL Server security isn't quite that simple.

When a stored procedure is created, the database engine checks the permissions of the creator to perform all of the operations in the procedure. If the creator is lacking any of the permissions needed for any statement in the stored procedure, it won't compile successfully.

When a stored procedure is executed, the database engine only checks to see if the current user has permission to execute the stored procedure.

This allows a privileged user like dbo to create a stored procedure that can be executed by an "underprivileged" user that contains DML that the user could not execute directly. It allows the creator to "delegate" their privileges in a controlled way.

There are a few exceptions to this, but the only exception that matters in many cases is dynamic SQL. SQL Server executes dynamic SQL in a different context, almost like the current user created a new spid for the dynamic SQL. That is why @.variables can't be referenced in dynamic SQL, and it is also why the user needs to have permission to execute any DML statements that are executed dynamically.

-PatP|||Brett,

By the question "What do you have to do?" I take you mean what is my job here? It is simply creating reports for loan data. There are several steps required but basically updating data from a temporary table that has its data destroyed every fifteen minutes, deduping, grouping, and sorting and that sort of fun stuff.

I don't think there will be a place to hide. I will either be granted privileges to do this or not.

ddave|||If you are working for a large company there has to be a DBA or at least an IS contact who is responsible for this. You need to have them give you db_datareader access. You can then create procedures and have THEM place them on the production server after reviewing them.

And, tell them to get a development environment. If they are a large company, I'm sure they can afford it.

Sunday, February 19, 2012

Can a stored procedures result set be returned

Pls give some samplesOriginally posted by bennydubai
Pls give some samples

create procedure theExample as
select * from sysobjects|||Got it!!! Thanks............getting the column count in tables.

select sysobjects.name,count(*) from sysobjects
join syscolumns on syscolumns.id=sysobjects.id
where sysobjects.xtype='u'
group by sysobjects.name|||OR BETTER THIS WAY

SELECT
count(*)
FROM INFORMATION_SCHEMA.COLUMNS
where table_name='staff'

Sunday, February 12, 2012

Calling Visual Foxpro 7 COM

Dear Experts,

We are creating instances of COM Objects written in Visual FoxPro 7 in our SQL Server 2005 stored procedures.
The problem is that VFP Automation Manager which shows number of connections to number of objects is showing 3 connections to 3 objects(instead 1 to 1).

We are releasing the object in SQL Server 2005 using the sp_OADestroy @.Object but the Automation Manager leaves 1 connection to 1 object.

The Automation manager connection doesn't release all the connections.

What effects is this having to our SQL Server 2005 installation and how can we avoid it?

We noticed that when we stop the SQL Service, connections to the Automation Manager are also released.

Thank you for your time.

Regards,

Spyros Christodoulou

You could stop the OLE Automation execution environment itself by calling sp_OAStop. Note that this affects the execution environment at the server-level. Generally, you should avoid using OLE automation extensively since it is resource intensive and running these in-proc can destabilize the server. Try creating the ole server out-of-proc for better reliability with some performance penalty. What is the reason for calling the VFP object from TSQL? Is this absoultely necessary? Note that you can perform queries against VFP databases/tables using linked servers. This is something you should look at also.|||Dear Umachandar,

Thanks for your reply.

Unfortunately we cannot stop OLE Automation execution environment because other users may executing OLE Methods as well.

The reason we are calling VFP from TSQL is that we need VFP to export some files.
I know that we could use a linked server, but in our case it doesn't apply because of the following:
1) VFP database and tables are changing a lot and we don't want the SQL team to be involved every time the VFP team changes tables required for the Import in SQL.
2) The export process is very complicated and it may need to call 2 or 3 VFP methods which means on a change we need to look into these methods as well. (Both VFP and SQL Teams)

For these reasons and the fact that it is much faster to develop the export method in VFP it is better to call VFP method to export data for SQL server.

Have you tried calling VFP out-of-proc COM objects? Does it properly release memory when you call sp_OADestroy @.Object ?

Regards,

Spyros Christodoulou
|||I was suggesting out-of-proc instantiation for better reliability/isolation on the server-side. Some of this might be just behavior of OLE automation. Can you try similar test from say VB and see if the connections are released properly after the OLE object is destroyed?|||Hi Umachandar,

Thanks for your reply,

I found a post you made at microsoft.public.sqlserver.programming on august of 2001.

"I have used this. It works perfectly fine. Are you making a EXE? Does it

have UI? Make sure it doesn't have any of those. Here is one sample:

NOTE -- Save this to a file called "VFPOLE.PRG" in "C:\TEMP"
DEFINE CLASS vfpole AS Custom OLEPUBLIC
prop1 = 'VFPOLE'
ENDDEFINE

NOTE Run these in the VFP command window
CD C:\Temp
BUILD PROJECT VFPOLE FROM VFPOLE.PRG
BUILD DLL VFPOLE FROM VFPOLE

-- Now run this on the SQL Server

declare @.o int, @.h int, @.p varchar( 255 )

exec @.h = sp_OACreate 'VFPOLE.VFPOLE', @.o out

if @.@.error|@.h <> 0 exec sp_displayoaerrorinfo @.o, @.h

print @.o

exec @.h = sp_OAGetProperty @.o, 'Prop1', @.p OUT

if @.@.error|@.h <> 0 exec sp_displayoaerrorinfo @.o, @.h

print @.p

exec sp_oadestroy @.o"

I tried it and it works as an in-process OLE server. It seems that it concumes some SQL Server memory every time I run it. How to register and call the dll if it resides on a different server. (like when you register the VFP .vbr file using clireg32.exe)

Do you know how to make it an out of process and called it based on the following scenario:

Server 1: VFP Database
Server 2: SQL Server

I need to run (SP on Server 2) the dll or exe using Ole Automation on Server 1. (Server 2 will have share access on Server 1)

Any help will be greatly appreciated.

Thanks again,

Spyros Christodoulou

|||The third parameter to sp_OACreate specifies the context for the OLE server. If you specify it as 4 then out-of-proc activation will take place. See Books Online for more details on the parameter.|||

Hi Umachandar and Spyros:

I am trying to do something very similar in SQL Server 2000 with VFP 8 objects.

The remaining problem is also similar as the one Spyros described:

"(...)

Server 1: VFP Database
Server 2: SQL Server

I need to run (SP on Server 2) the dll or exe using Ole Automation on Server 1. (Server 2 will have share access on Server 1)

(...)"

In server 1, I have the COM+ application o package correctly installed and working since years

In Clients computers various front end consume the server classes via, for example in VB

CreateObject('AppMastervs.cOrga', mtsServer1)

or in VFP

CreateObjectEx('AppMastervs.cOrga', mtsServer1)

These clients has registered the corresponding .vbr & tlb via CliReg32

I also registered the server classes in the Server 2 (the one with SQLServer) and it work fine with the Front ends, but was impossible to me to create the class in SQLServer using

EXEC @.hr = sp_OACreate 'AppMastervs.cOrga', @.object OUT ,1

EXEC @.hr = sp_OACreate 'AppMastervs.cOrga', @.object OUT ,4

EXEC @.hr = sp_OACreate 'AppMastervs.cOrga', @.object OUT ,5

Then I copied and registered the class as local in the the Server 2 (as COM+ app in Component services) and then it worked fine (with the 3rd parameter in 4 or 5), but the problem is that must not be done beacuse this carges the sqlServer, generate unnecesary traffic and dificults the server update process.

So, please let me know if is really possible to create, in SQL Server 2000, a server class working as COM+ application in other server, without register it locally as COM+ Application.

Thanks in advance;

Claudio Facundo Lacivita

Calling Visual Foxpro 7 COM

Dear Experts,

We are creating instances of COM Objects written in Visual FoxPro 7 in our SQL Server 2005 stored procedures.
The problem is that VFP Automation Manager which shows number of connections to number of objects is showing 3 connections to 3 objects(instead 1 to 1).

We are releasing the object in SQL Server 2005 using the sp_OADestroy @.Object but the Automation Manager leaves 1 connection to 1 object.

The Automation manager connection doesn't release all the connections.

What effects is this having to our SQL Server 2005 installation and how can we avoid it?

We noticed that when we stop the SQL Service, connections to the Automation Manager are also released.

Thank you for your time.

Regards,

Spyros Christodoulou

You could stop the OLE Automation execution environment itself by calling sp_OAStop. Note that this affects the execution environment at the server-level. Generally, you should avoid using OLE automation extensively since it is resource intensive and running these in-proc can destabilize the server. Try creating the ole server out-of-proc for better reliability with some performance penalty. What is the reason for calling the VFP object from TSQL? Is this absoultely necessary? Note that you can perform queries against VFP databases/tables using linked servers. This is something you should look at also.|||Dear Umachandar,

Thanks for your reply.

Unfortunately we cannot stop OLE Automation execution environment because other users may executing OLE Methods as well.

The reason we are calling VFP from TSQL is that we need VFP to export some files.
I know that we could use a linked server, but in our case it doesn't apply because of the following:
1) VFP database and tables are changing a lot and we don't want the SQL team to be involved every time the VFP team changes tables required for the Import in SQL.
2) The export process is very complicated and it may need to call 2 or 3 VFP methods which means on a change we need to look into these methods as well. (Both VFP and SQL Teams)

For these reasons and the fact that it is much faster to develop the export method in VFP it is better to call VFP method to export data for SQL server.

Have you tried calling VFP out-of-proc COM objects? Does it properly release memory when you call sp_OADestroy @.Object ?

Regards,

Spyros Christodoulou
|||I was suggesting out-of-proc instantiation for better reliability/isolation on the server-side. Some of this might be just behavior of OLE automation. Can you try similar test from say VB and see if the connections are released properly after the OLE object is destroyed?|||Hi Umachandar,

Thanks for your reply,

I found a post you made at microsoft.public.sqlserver.programming on august of 2001.

"I have used this. It works perfectly fine. Are you making a EXE? Does it

have UI? Make sure it doesn't have any of those. Here is one sample:

NOTE -- Save this to a file called "VFPOLE.PRG" in "C:\TEMP"
DEFINE CLASS vfpole AS Custom OLEPUBLIC
prop1 = 'VFPOLE'
ENDDEFINE

NOTE Run these in the VFP command window
CD C:\Temp
BUILD PROJECT VFPOLE FROM VFPOLE.PRG
BUILD DLL VFPOLE FROM VFPOLE

-- Now run this on the SQL Server

declare @.o int, @.h int, @.p varchar( 255 )

exec @.h = sp_OACreate 'VFPOLE.VFPOLE', @.o out

if @.@.error|@.h <> 0 exec sp_displayoaerrorinfo @.o, @.h

print @.o

exec @.h = sp_OAGetProperty @.o, 'Prop1', @.p OUT

if @.@.error|@.h <> 0 exec sp_displayoaerrorinfo @.o, @.h

print @.p

exec sp_oadestroy @.o"

I tried it and it works as an in-process OLE server. It seems that it concumes some SQL Server memory every time I run it. How to register and call the dll if it resides on a different server. (like when you register the VFP .vbr file using clireg32.exe)

Do you know how to make it an out of process and called it based on the following scenario:

Server 1: VFP Database
Server 2: SQL Server

I need to run (SP on Server 2) the dll or exe using Ole Automation on Server 1. (Server 2 will have share access on Server 1)

Any help will be greatly appreciated.

Thanks again,

Spyros Christodoulou

|||The third parameter to sp_OACreate specifies the context for the OLE server. If you specify it as 4 then out-of-proc activation will take place. See Books Online for more details on the parameter.|||

Hi Umachandar and Spyros:

I am trying to do something very similar in SQL Server 2000 with VFP 8 objects.

The remaining problem is also similar as the one Spyros described:

"(...)

Server 1: VFP Database
Server 2: SQL Server

I need to run (SP on Server 2) the dll or exe using Ole Automation on Server 1. (Server 2 will have share access on Server 1)

(...)"

In server 1, I have the COM+ application o package correctly installed and working since years

In Clients computers various front end consume the server classes via, for example in VB

CreateObject('AppMastervs.cOrga', mtsServer1)

or in VFP

CreateObjectEx('AppMastervs.cOrga', mtsServer1)

These clients has registered the corresponding .vbr & tlb via CliReg32

I also registered the server classes in the Server 2 (the one with SQLServer) and it work fine with the Front ends, but was impossible to me to create the class in SQLServer using

EXEC @.hr = sp_OACreate 'AppMastervs.cOrga', @.object OUT ,1

EXEC @.hr = sp_OACreate 'AppMastervs.cOrga', @.object OUT ,4

EXEC @.hr = sp_OACreate 'AppMastervs.cOrga', @.object OUT ,5

Then I copied and registered the class as local in the the Server 2 (as COM+ app in Component services) and then it worked fine (with the 3rd parameter in 4 or 5), but the problem is that must not be done beacuse this carges the sqlServer, generate unnecesary traffic and dificults the server update process.

So, please let me know if is really possible to create, in SQL Server 2000, a server class working as COM+ application in other server, without register it locally as COM+ Application.

Thanks in advance;

Claudio Facundo Lacivita

Friday, February 10, 2012

Calling Stored procedures via the Job Agent - Please help!

Hi all,
My colleague and I are struggling with a rather annoying problem. The
situation is as follows:
We've two database servers (one primary and one backup) with
SQL-server 2000 installed. We've been trying to implement
"log-shipping" on this server using the example scripts from the SQL
server 2000 resource kit. What happens in these scripts is basically
the following.
Server A: starts the (local) stored procedure (sproc) sp_logship
Server A: sp_logship copies the transactionlog into a shared location,
so Server B is able to reach the transactionlog.
Server A: calls a sproc on Server B.
Server B: The sproc looks for a transactionlogfile in the shared
location and restores Server B's database using this logfile.
This mechanism works fine when we call "sp_logship" from the
Query-analyzer on Server A.
When we try to run start the "sp_logship" using the Job Agent (also on
Server A), we get the following error:
Msg 7410, sev 16: Remote access not allowed for Windows NT user
activated by SETUSER [SQLSTATE 42000]
We tried to solve this problem by creating several other users, even
ones who use SQL server Authentication. It was to no avail.
I hope someone can help me with this problem,
Thank you very much in advance,
Alke WiebengaIs the SQL Server Agent startup account a domain one with permission to
access the shared folder in both servers?
AMB
"A. Wiebenga" wrote:

> Hi all,
> My colleague and I are struggling with a rather annoying problem. The
> situation is as follows:
> We've two database servers (one primary and one backup) with
> SQL-server 2000 installed. We've been trying to implement
> "log-shipping" on this server using the example scripts from the SQL
> server 2000 resource kit. What happens in these scripts is basically
> the following.
> Server A: starts the (local) stored procedure (sproc) sp_logship
> Server A: sp_logship copies the transactionlog into a shared location,
> so Server B is able to reach the transactionlog.
> Server A: calls a sproc on Server B.
> Server B: The sproc looks for a transactionlogfile in the shared
> location and restores Server B's database using this logfile.
> This mechanism works fine when we call "sp_logship" from the
> Query-analyzer on Server A.
> When we try to run start the "sp_logship" using the Job Agent (also on
> Server A), we get the following error:
> Msg 7410, sev 16: Remote access not allowed for Windows NT user
> activated by SETUSER [SQLSTATE 42000]
> We tried to solve this problem by creating several other users, even
> ones who use SQL server Authentication. It was to no avail.
> I hope someone can help me with this problem,
> Thank you very much in advance,
> Alke Wiebenga
>

Calling Stored Procedures using plain ADO in C#

Hello All,

We are trying to figure out how to make a stored procedure call and pass some inputs using C# and plain ADO. We are able to call an empty stored procedure but cannot pass parameters into a stored procedure.

Does anyone have sample code in C# whereby we can open a connection and pass inputs into a stored procedure? The following is a sample code we are using:

ADODB.Parameter param = new ADODB.Parameter();

param=cmd.CreateParameter("@.StoreID", ADODB.DataTypeEnum.adInteger, ADODB.ParameterDirectionEnum.adParamInput,sizeof(int) , 9);

cmd.Parameters.Append(param);

ADODB.Recordset rsInv = cmd.Execute(out objAffected, ref objAffected,-1 );

In the above example, we create a parameter of type integer and try to add it to the ADO Command object. It is supposed to return a recordset. It returns a recordset with record count -1.

Sincerely,

Dwight Kulkarni


Did you check the EOF property for the Recordset? The RecordCount property is not always an accurate indicator of how many rows have been returned, and in some instances will return a value of -1 (such as for a forward-only cursor).|||

It was a simple thing of course, the cursor location was EOF.

Thanks.

calling stored procedures on different servers

I'm using reporting services to build a report and I plan on using a stored procedure to gather my data for the report. My question is:

I know it's possible to call a stored procedure from a stored procedure, both within the same dB and in different dB's, but is it possible to call a SP that's on a different server? My gut says "definitely not. at least not easily." But I wanted to see if anyone had any thoughts on this before I pursue a different course of action.Lookup "Linked Server" in books online and you will get lots of information on linking servers, which should then allow you to execute the SP on another server.|||Do you have any examples or know where I can find some of a stored procedure that uses a linked server? thanks for the help!

jonathan|||Actually, I got it to work. Thanks again!

jonathan

Calling Stored Procedures in SQL Statement

How can we call Stored Procedure inside any SQL Statement

For Example.

If we have procedure name sprocCurrentPriority

select * from tablename where colmunname = exec sprocCurrentPriority

Try with this:

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString);
SqlCommand command = conn.CreateCommand())
conn.Open();
command.CommandText = "sprocCurrentPriority";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@.colmunname", SqlDbType.DateTime).Value = DateTime.Now;
command.ExecuteNonQuery();
conn.Close();

|||

What can of output the stored procedure will return?

If it is an OUTPUT parameter, then the statment will be:

1EXEC MyStoredProcedure @.MyOuputParameterint23SELECT *FROM MyTableWhere MyColumn = @.MyOutputParameter

If the output is a result set, the you can load it into a table then do what you want to do with it :)

1Insert into MyTable2exec MyStoerdProcedure
 Note: The returned result set must match the "MyTable" strcture.
 
Good luck.
|||

EXEC MyStoredProcedure @.MyOuputParameterint

SELECT *FROM MyTableWhere MyColumn = @.MyOutputParameter

Ok.

But when this query will change to

EXEC MyStoredProcedure @.MyOuputParameterint

SELECT top 3 FROM MyTableWhere MyColumn = @.MyOutputParameter

Now for all 3 rows the value of @.MyOutputParameter will same.

But I want that for every row it will re execute the procedure and get the new value.

|||

zeeshanuddinkhan@.hotmail.com:

EXEC MyStoredProcedure @.MyOuputParameterint

SELECT *FROM MyTableWhere MyColumn = @.MyOutputParameter

Ok.

But when this query will change to

EXEC MyStoredProcedure @.MyOuputParameterint

SELECT top 3 FROM MyTableWhere MyColumn = @.MyOutputParameter

Now for all 3 rows the value of @.MyOutputParameter will same.

But I want that for every row it will re execute the procedure and get the new value.

So, lets your stored procedure return the output as a result set.
Then load (or insert) the result set in a table (must both the result set and the table have the same strcture).
Then your query will be:

1SELECT top 3FROM MyTableWhere MyColumnin2 (3Select MyColumnValue4From MyTableHavingTheResultSet5 )6GO

This will do the job; getting top 3 records that match the criteria (condition) you got from the stored procedures [more than a value]

Good luck..

|||

CS4Ever, does a stored procedure be able to return a result set? i thoght it can only return integer value. Could you please show me an example? I would really appreciate your help :)

|||

Bo Chen – MSFT:

CS4Ever, does a stored procedure be able to return a result set? i thoght it can only return integer value. Could you please show me an example? I would really appreciate your help :)

Hi Bo Chen,
Actually once I read your post I become surprised, then when I think again I though you become cofused when I wrote in my last post "stored procedure return result set".
What I meant by return (in my last post) is NOT the Return statment in stored procedure, but this (see the example):

1CREATE PROCEDURE MyStoredProcedure23AS45SET NOCOUNT ON67SELECT EmpID, EmpName, EmpDep8FROM EmployeeTable910SET NOCOUNT OFF

I hope things become clear now :)

Good luck.

|||

Got it . thanks :)

Calling Stored Procedures in a Select Statement

I am trying to call a stored procedure inside a SQL SELECT statement. Has anybody had to do this in the past? I have a SELECT statement in a Microsoft Access database and I need that SELECT statement to call the stored procedure in the SQL server. Any help would be appreciatedAh, in a word, No.

BUT!

Use a passthru query and do

EXEC procedurename;|||If you are going to try joining into the result set from your stored procedure, this is generally frowned upon (when allowed at all) because a procedure can conceivable return more than one result set, and could even modify data during execution that is also reference by your SQL statement. Confusion results.

If possible, rewrite your stored procedure as a view or as a user-defined table function.|||I figured it out. I had to do was create the function below:

CREATE FUNCTION dbo.udfMonthlyIncome
(
@.salary int
,@.frequency int
)
RETURNS int AS
BEGIN
Return
(
SELECT CASE @.frequency
WHEN 1 /*'Bi-Weekly'*/ THEN (@.salary * 26) / 12
WHEN 2 /*'Daily'*/ THEN @.salary * 20
WHEN 3 /*'Hourly'*/ THEN (@.salary * 40 * 52) / 12
WHEN 4 /*'Monthly'*/ THEN @.salary
WHEN 5 /*'Quarterly'*/ THEN @.salary / 3
WHEN 6 /*'Semi-Annual'*/ THEN @.salary / 6
WHEN 7 /*'Semi-Monthly'*/ THEN @.salary * 2
WHEN 8 /*'Weekly'*/ THEN (@.salary * 52) / 12
WHEN 9 /*'Annual'*/ THEN @.salary / 12
ELSE 0
END as Income
)
END

Then I can call the function like this:

Select dblSalary, dbo.udfMonthlyIncome(dblSalary,lngFrequency) as MonthlyIncome
from tblIncome

Thanks for the help guys|||Way to go!

calling Stored Procedures from different DBs

Is it possible to have a stored procedure in database A while calling
it from database B and have it manipulate the tables in database B
(whatever the calling database happens to be)?

We have a large-scale app that uses many complex stored procedures,
and as of now, we're copying the SPs to every new database that is
created, and it will soon become a nightmare for propagating updates
and fixes. We'd like to keep a master set of the SPs in one DB and
"use" them from other DBs so that they only query data and manipulate
tables in the calling DB. I hope someone has some suggestions. Thanks.ZeBerg (adam@.alumni.northwestern.edu) writes:
> Is it possible to have a stored procedure in database A while calling
> it from database B and have it manipulate the tables in database B
> (whatever the calling database happens to be)?
> We have a large-scale app that uses many complex stored procedures,
> and as of now, we're copying the SPs to every new database that is
> created, and it will soon become a nightmare for propagating updates
> and fixes. We'd like to keep a master set of the SPs in one DB and
> "use" them from other DBs so that they only query data and manipulate
> tables in the calling DB. I hope someone has some suggestions. Thanks.

While this is possible, this will bring out of the frying pan, and into
the fire.

You would have to use dynamic SQL to manipulate the tables, and then
many of the advantages of stored procedures would go out the window.

OK, so there is the possibility of adding your own system procedures in
the master database, but this is unsupported, has security issues and
and I am not even sure whether it works with next version of SQL Server.

And neither of these schemes works the day you decide to scale out and
have databases one more than one server. Or the day you want to a test
version of the app running against a test database on the same server.

So what is left? Do as you do know, that is the way to go. What you
apparently need, is to invest time in how to deploy changes in a
controlled way. A foundation for this is to use a version-control
system. It is from the VCS you build update scripts to deploy the
changes. You might higher levels of sophistication, and there are
a number of third-party tools out there which aim specifically at
configuration management with SQL Server.

Since my shop in the same as yours - except that our multiple databases
are both in-house and remote customer sites - we have developed our
own routines, and the tool we use is actually available as freeware,
see http://www.abaris.se/abaperls/.

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

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

Calling stored procedures from C#

Hi All... I'm calling a stored procedure from C#. I'm sending it input parameters as follows:

SqlCommand c =newSqlCommand("AddAuthor", myConnection);
c.CommandType =CommandType.StoredProcedure;

c.Parameters.Add(newSqlParameter("@.LastName",SqlDbType.VarChar, 100));
c.Parameters["@.LastName"].Value ="Last";

c.Parameters.Add(newSqlParameter("@.FirstName",SqlDbType.VarChar, 100));
c.Parameters["@.FirstName"].Value ="First";

In my opinion, that works nice - and it's easy. The reference I'm using says I can also specify "output" parameters - instead of supplying a value, one needs to change a property called direction.

But my stored procedure doesnt return any output parameters per se, but it does return a value. That is the last statement in the stored procedure is "RETURN@.@.IDENTITY" - it returns the identity field after an INSERT... So how do I get that value back in my C# code?

Thanks for the help in advance. Happy 4th to all! : ) -- Curt

If you do

SELECT @.@.IDENTITY in your stored procedure, you can get the value with

c.ExecuteScalar();

I do not know if this will work with the RETURN statement,thoughSmile

|||

To use an output parameter, you need to add an output parameter to your SqlCommand prior to execution, like:

SqlParameter output =new SqlParameter("@.Return_Value", SqlDbType.VarChar, 100);output.Direction = ParameterDirection.Output;c.Parameters.Add(output);

When you execute your SP, you need to set the value. Then you can get the new value from the parameter.

This article is based around using a SqlDataSource, but it has details on the SP updateshttp://aspnet.4guysfromrolla.com/articles/050207-1.aspx.

I'd also take a look herehttp://msdn2.microsoft.com/en-gb/library/ms190315.aspx at the difference between @.@.IDENTITY and SCOPE_IDENTITY (my guess is SCOPE_IDENTITY is what you really want).

Hope that helps.

Aaron

|||

dt...

Yeah, when I added the "SELECT" to my SPROC, it worked fine - thanks for the tip. And yeah, as you suspected it didn't work for the "RETURN" - I had to add the "SELECT" to my SPROC. No problem though...

Athens, eh? Well, that goes back a couple of thousand years, doesn't it? ; ) Thanks for the help!

Curt

|||

Smile however, if you want to get multiple values from your database you should use output parameters, just like agolden described. Moreover, if you use SQL Server 2005, you should use SCOPE_IDENTITY, as agolden also stated.