Showing posts with label procedure. Show all posts
Showing posts with label procedure. Show all posts

Thursday, March 29, 2012

extract just the date from a datetime field using T-SQL

I am using a calendar control to pass a date to a stored procedure. The field in the table is a datetime field. Is it possible to extract just the date from the datetime field, or do I have to use multiple Datepart?

WHERE (datepart(mm,sampletimestamp) = month(@.selcteddate) and
datepart(dd,sampletimestamp) = day(@.selcteddate) and
datepart(yyyy,sampletimestamp) = year(@.selcteddate)
)

This works, but I thought there must be an easier way.

There are many ways. Easiest is to do below:

convert(varchar, sampletimestamp, 112) = @.selcteddate

|||

Something like this:

select DATEADD(DAY, 0, DATEDIFF(DAY, 0, GETDATE())),
DATEADD(DAY, 1, DATEDIFF(DAY, 0, GETDATE()))

-- --
2007-01-10 00:00:00.000 2007-01-11 00:00:00.000

And best to use a form like this for your where:

WHERE sampletimestamp >= DATEADD(DAY, 0, DATEDIFF(DAY, 0, @.selcteddate))
and sampletimestamp < DATEADD(DAY, 1, DATEDIFF(DAY, 0, @.selcteddate))

So you can increase the likelihood of using an index for the search, since you don't have to execute a function on the column (which makes it unusable as a search argument for an index lookup.)

Extract a string in a Stored Procedure

Is there anyway to extract part of a string in a stored procedure
using a parameter as the starting point?
For example, my string might read: x234y01zx567y07zx541y04z
My Parameter is an nvarchar and the value is: "x567y"
What I want to extract is the two charachters after the parameter, in
this case "07".
Can anyone shed some light on this problem?
Thanks,
lqLauren Quantrell (laurenquantrell@.hotmail.com) writes:
> Is there anyway to extract part of a string in a stored procedure
> using a parameter as the starting point?
> For example, my string might read: x234y01zx567y07zx541y04z
> My Parameter is an nvarchar and the value is: "x567y"
> What I want to extract is the two charachters after the parameter, in
> this case "07".
> Can anyone shed some light on this problem?

Looks like a combination of substring and charindex (or possibly
patindex) is what you need. I recommend that you use the SQL Server
Books Online to study all the string functions that SQL Server
offers. They are not that many, and not that extremely powerful, but
it's very useful to know them.

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

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||Thanks.
I'm on a crash project using MDSE and don't have immediate access to
Books Online though...
lq

Erland Sommarskog <sommar@.algonet.se> wrote in message news:<Xns946FEC5AC5081Yazorman@.127.0.0.1>...
> Lauren Quantrell (laurenquantrell@.hotmail.com) writes:
> > Is there anyway to extract part of a string in a stored procedure
> > using a parameter as the starting point?
> > For example, my string might read: x234y01zx567y07zx541y04z
> > My Parameter is an nvarchar and the value is: "x567y"
> > What I want to extract is the two charachters after the parameter, in
> > this case "07".
> > Can anyone shed some light on this problem?
> Looks like a combination of substring and charindex (or possibly
> patindex) is what you need. I recommend that you use the SQL Server
> Books Online to study all the string functions that SQL Server
> offers. They are not that many, and not that extremely powerful, but
> it's very useful to know them.|||I figured out how to do this:

substring(mystring,charindex(@.parameter,myString)+ len(@.parameter),2)

where @.parameter = 'x' + [myUserID] + 'y'

Thanks for pointing me in the right direction.

lq

Erland Sommarskog <sommar@.algonet.se> wrote in message news:<Xns946FEC5AC5081Yazorman@.127.0.0.1>...
> Lauren Quantrell (laurenquantrell@.hotmail.com) writes:
> > Is there anyway to extract part of a string in a stored procedure
> > using a parameter as the starting point?
> > For example, my string might read: x234y01zx567y07zx541y04z
> > My Parameter is an nvarchar and the value is: "x567y"
> > What I want to extract is the two charachters after the parameter, in
> > this case "07".
> > Can anyone shed some light on this problem?
> Looks like a combination of substring and charindex (or possibly
> patindex) is what you need. I recommend that you use the SQL Server
> Books Online to study all the string functions that SQL Server
> offers. They are not that many, and not that extremely powerful, but
> it's very useful to know them.|||Lauren Quantrell (laurenquantrell@.hotmail.com) writes:
> I'm on a crash project using MDSE and don't have immediate access to
> Books Online though...

You have. Check my signature.

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

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

Extract "GroupName" from "sp_helpuser"

Hi all,

I want to create a stored procedure which will extract the "GroupName"
from the record returned by "sp_helpuser". In order to do this I need
to execute "sp_helpuser" which returns the entire record. I want to
just extract the "GroupName" from the record and return it to my
application. How do I go about this?

Thanks in advance,

AlvinAlvin Sebastian (asebastian@.cmri.usyd.edu.au) writes:
> I want to create a stored procedure which will extract the "GroupName"
> from the record returned by "sp_helpuser". In order to do this I need
> to execute "sp_helpuser" which returns the entire record. I want to
> just extract the "GroupName" from the record and return it to my
> application. How do I go about this?

Either you access sysusers directly, you can use the INSERT EXEC construct:

INSERT #temp (...)
EXEC sp_helpuser

You need to create #temp so that it agrees with the output from sp_helpuser.

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

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

By the way, I forgot to mention in the first post that I'm only
interested in the "GroupName" of the currently logged-on user so the
stored procedure will be returning a single string value only and not
a table. How should the stored procedure return this single value from
the record returned by "sp_helpuser"?

Alvin

Erland Sommarskog <sommar@.algonet.se> wrote in message news:<Xns93BF646E19EF7Yazorman@.127.0.0.1>...
> Alvin Sebastian (asebastian@.cmri.usyd.edu.au) writes:
> > I want to create a stored procedure which will extract the "GroupName"
> > from the record returned by "sp_helpuser". In order to do this I need
> > to execute "sp_helpuser" which returns the entire record. I want to
> > just extract the "GroupName" from the record and return it to my
> > application. How do I go about this?
> Either you access sysusers directly, you can use the INSERT EXEC construct:
> INSERT #temp (...)
> EXEC sp_helpuser
> You need to create #temp so that it agrees with the output from sp_helpuser.|||Alvin Sebastian (asebastian@.cmri.usyd.edu.au) writes:
> By the way, I forgot to mention in the first post that I'm only
> interested in the "GroupName" of the currently logged-on user so the
> stored procedure will be returning a single string value only and not
> a table. How should the stored procedure return this single value from
> the record returned by "sp_helpuser"?

A one-row result set is still a table.

There is the OPENQUERY method as well.

See http://www.algonet.se/~sommar/share_data.html where I discuss both
methods.

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

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||Thanks Erland, I got it working now!

Tuesday, March 27, 2012

Extra parameters being added onto SP call with ADO?

We are running into problems on our development environment with extra
parameters being added on to a stored procedure call. Instead of the
expected stored procedure call, the trace shows something like this:

declare @.P1 int
set @.P1=NULL
<<expected stored procedure call>> , @.P1 output, <<repeat of first
three sp parms>>
select @.P1

The developer has checked the code, and I have checked the SP - both
seem to match what is in production (which works fine). The databases
are on the same server, and the apps are running on seperate web
servers.

I'm guessing this may be some sort of configuration issue with ADO,
SQL, or something else - has anyone run into something similar to
this? Thanks!

DaveSo, is the sp running at all when called with that additional parameter? It
should fail if that parameter (the one you think is additional) is not
declared in the sp.

What happens if you paste the output from Profiler into Query Analyzer and
run it?
--
HTH,
Vyas, MVP (SQL Server)
http://vyaskn.tripod.com/
Is .NET important for a database professional?
http://vyaskn.tripod.com/poll.htm

"Dokter Z" <dzahn@.execpc.com> wrote in message
news:7e6a5a6.0402250644.4ef950eb@.posting.google.co m...
We are running into problems on our development environment with extra
parameters being added on to a stored procedure call. Instead of the
expected stored procedure call, the trace shows something like this:

declare @.P1 int
set @.P1=NULL
<<expected stored procedure call>> , @.P1 output, <<repeat of first
three sp parms>>
select @.P1

The developer has checked the code, and I have checked the SP - both
seem to match what is in production (which works fine). The databases
are on the same server, and the apps are running on seperate web
servers.

I'm guessing this may be some sort of configuration issue with ADO,
SQL, or something else - has anyone run into something similar to
this? Thanks!

Dave|||Vyas -

Thanks for the response. Actually, we have discovered that the initial
problem was caused by

1) Some "sub-optimal" Paramaters.Refresh code
2) A stored procedure call issued by user aaaaa ended up calling
bbbbb.stored_proc_name instead of dbo.stored_proc_name. I'm currently
researching that issue...

Dave

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

External stored procedure, performance?

Hi everybody,
I should begin to write a DLL library for Sql2000 server.
The functions I like to implement are mathematical functions, like standard
deviation, and similar, nothing really complex. Often I have to use more
then one standard deviation inside the sama function, using subset of a
record set.
Of course I can use sql2000, that implemets standard deviation and basic
mathematical function, so the question is: is it opportune to write a DDL to
improve performance, or is it worse, or just the same?
thanks a lot for any kindly advice
cesareI think the key words here are "using a subset of a recordset". Based on
that I would implement it in T-SQL, or on the application side but not in an
XP. The cost of connecting back to the SQL Server to grab a subset of rows
is going to be big, especially if you perform this std dev calc several
times in a row.
"Cesare" <cvairetti@.mcgestioni.it> wrote in message
news:uO9XdpvjGHA.1640@.TK2MSFTNGP02.phx.gbl...
> Hi everybody,
> I should begin to write a DLL library for Sql2000 server.
> The functions I like to implement are mathematical functions, like
> standard
> deviation, and similar, nothing really complex. Often I have to use more
> then one standard deviation inside the sama function, using subset of a
> record set.
> Of course I can use sql2000, that implemets standard deviation and basic
> mathematical function, so the question is: is it opportune to write a DDL
> to
> improve performance, or is it worse, or just the same?
> thanks a lot for any kindly advice
> cesare
>sql

Monday, March 26, 2012

External Stored Procedure in SQL Server 2005(x64)

I have generated a DLL file in VC++ 2005 by a 'C' file. It works fine when I put in a 32bits machine(32bits Windows Server 2003 + 32 bits SQL Server 2005).

However, when I build it into 64 bits, it doesn't work in a 64 bits machine. I have checked by Dependenct Walker, the DLL generated is linked with KERNEL32.DLL / OPENDS60.DLL / MSVCR80D.DLL, all of these DLL files are on the 64 bits machines and linked correctly.

I used the command


sp_addextendedproc 'abc', 'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Binn\abc.dll'

to create a ext. stored procedure. When I run it, the error message shows that

Could not load the DLL C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Binn\abc.dll, or one of the DLLs it references. Reason: 126(error not found).

I would like to ask what is cause of the problem? Do I need to use CLR instead?

Thank you very much!!~

BTW, it is because of your thread I posted the "32Bit Vs 64Bit" SQLCLR platform differences thread. If there are any definite differences this would be a great addition to my upcoming book. Have you experienced any other problems on 64bit platform for sqlclr?

thanks,

derek

external stored procedure (DLL) in Java?

Hi,

I am going to be writing an external stored procedure (my first) for SQL server 2000.

Has anyone out there written a DLL in Java (J++ or .NET) and then accessed the functions within the DLL as an external stored procedure in T/SQL?

I ask the question becaues I'm likely to get it done considerably faster if I write it in Java then VB ;-)

Any advice / suggestions most welcome.

Cheers,

EwanIt shouldn't really make a difference what language you write your dll in. As long as its compiled as a dll, you should be able to call it from a Stored Proc.

Just ensure that the dll is registered on the server that as executing the StoredProc (not the client).

As far as I know , there is no way to return values from the dll into the Stored Proc. Please let me know if there is.

I take no credit for the information below. I copied it from an old posting and saved it, and I cannot remember who posted it originally.

Good luck.

Lionel.

You can do it with the SP_OA* extened stored procedures, located in the
MASTER database (of ms-sql 7.0/2000). Look at this example (for sending
email
through jmail);

CREATE PROCEDURE sp_Send_JMail

@.fromName as char(50),
@.fromEmail as char(50),
@.toName as char(50),
@.toEmail as char(50),
@.subject as char(100),
@.Body as char(500)

AS
DECLARE @.ObjTok int
DECLARE @.RetVal int

EXEC @.RetVal=sp_OACreate'JMail.SMTPMail',@.ObjTok OUT
EXEC sp_OASetProperty @.ObjTok, 'ServerAddress','yourmailserver.com'
EXEC sp_OASetProperty @.ObjTok, 'SenderName', @.fromName
EXEC sp_OASetProperty @.ObjTok, 'Sender', @.fromEmail
EXEC sp_OASetProperty @.ObjTok,'Subject', @.Subject
EXEC @.RetVal = sp_OAMethod @.ObjTok, 'AddRecipient', Null,@.toEmail
EXEC sp_OASetProperty @.ObjTok, 'Body', @.Body
EXEC @.RetVal = sp_OAMethod @.ObjTok, 'Execute'
EXEC sp_OADestroy @.ObjTok GO

External Procedure error

I'm trying to compile the following function:

CREATE OR REPLACE FUNCTION shell(cmd IN VARCHAR2)
RETURN PLS_INTEGER
AS
EXTERNAL LIBRARY EXTPROCSHELL_LIB
NAME "extprocsh"
LANGUAGE C
PARAMETERS (cmd STRING);

but keep getting an error that says EXTPROCSHELL_LIB needs to be declared. Somewhere I read that this probably means that the shared library doesn't exist and try recreating it.

Our DBA assures me that he created the library in the Oracle home lib directory and I do see the compiled C program there and also saw the path of his library creation and everything looks fine.

Any suggestions here?Hello,

do you have created a library object with the same name ?
See "CREATE LIBRARY ..."

The error you have posted does not mean, that you dont have created the lib in the oracle directory.
Its says, that Oracle can not find the library object that points to the library in the oracle directoy ...

Hope that helps ?

Manfred Peter
Alligator Company GmbH
http://www.alligatorsql.comsql

Friday, March 23, 2012

external access denied to update a config file

Hello,

I'm having an issue with a CLR Stored procedure. Everything works great in a 32 bit environment, I have a CLR SP that updates an xml file stored on a local drive. When I execute the Stored proc it does go and update what I want it to in a 32 bit system. When I run the CLR SP on a 64 bit cluster, I seem to have give the "everyone" group write permissions to my G: drive (which is where the file is located that I'm updating). What security context is this SP running under? I thought it would be either under the SQL Service account (which is a domain user in the local administrators group) or what I'm logged in as when I run it from Management Studio (which is a domain admin, also in the local administrators group). If I have given the local administrators group "Full Control" access to the G: drive, why isn't this enough? Why do I have to give the Everyone group write access?

The security context seems odd to me, it seems like it's not running as either one of those 2 users I mentioned, because if it was, then it should be able to update the xml file.

Any help appreciated. Here's the error I'm getting:

Msg 6522, Level 16, State 1, Procedure usp_XMLWriter, Line 0

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

System.UnauthorizedAccessException: Access to the path 'g:\ssisPackages\BuildCalendar\andy.dtsConfig' is denied.

System.UnauthorizedAccessException:

at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)

at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)

at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)

at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)

at System.Xml.XmlTextWriter..ctor(String filename, Encoding encoding)

at System.Xml.XmlDocument.Save(String filename)

at XMLWriter.StoredProcedures.usp_XMLWriter(String xmlDocPath, String xmlNodePath, String xmlInnerText)

.

I found out that I'm able to get this to work if I put the SQL Service User account directly into the security of the G: Drive. For some reason, even though the user is in the Local Administrators group, it doesn't seem to pick up the fact that my user in is in the group, and therefore won't let him update a file in the folder.

Does anyone know of any issues in a 64 bit cluster where a CLR Stored proc isn't able to decipher the users in a local Group?

|||This turned out to be a cluster issue. We weren't doing permissions through the cluster, we were doing permissions to the file shares through each node, which is a mistake in a cluster.

Wednesday, March 21, 2012

Extending CDOSYS Mail to include Query Attachments?

Hi,

I was wondering if anyone has extended the standard CDOSYS Mail Stored Procedure (SP) to allow it to send the results of a query as an attachment?

I have set up a SP for CDOSYS Mail as outlined in the following link:
http://support.microsoft.com/default.aspx?id=kb;de;312839&sd=tech

Currently I am using the old SQL Mail (xp_SendMail). But due to the problems with losing the MAPI connection and other limitations, I have been forced to find another solution. Using SQL Mail, I was able to add a query parameter and attach the results of the query to the email. I need to have the same functionality in CDOSYS Mail

Thanks,
KimHi,

I was wondering if anyone has extended the standard CDOSYS Mail Stored Procedure (SP) to allow it to send the results of a query as an attachment?

I have set up a SP for CDOSYS Mail as outlined in the following link:
http://support.microsoft.com/default.aspx?id=kb;de;312839&sd=tech

Currently I am using the old SQL Mail (xp_SendMail). But due to the problems with losing the MAPI connection and other limitations, I have been forced to find another solution. Using SQL Mail, I was able to add a query parameter and attach the results of the query to the email. I need to have the same functionality in CDOSYS Mail

Thanks,
Kim

Jasper has written an sp for it check it out here:
http://www.sqlteam.com/Forums/topic.asp?TOPIC_ID=20649|||Sorry, I don't think I explained myself very well!

I currently use xp_sendmail and pass a query as a parameter and attach the results of this query to an email. I would like to know if anyone has extended CDOSYS Mail to have the same functionality? Example of how I use this is in xp_sendmail @.query parameter would be a query which returns the total number of records on an import table and xp_sendmail sends the results in an email attachement OR sends the results as part of the body of the email.

Extract of the xp_sendmail Syntax:
xp_sendmail {[@.recipients =] 'recipients [;...n]'}
[,[@.query =] 'query']

[,[@.attach_results =] 'attach_value']|||I had the same problem and found a workaround using osql to write the results of the query to a file. I then include the file as an attachment and delete it from the server. Seems to work well even within a loop.

I used this to work from.
http://www.sqlteam.com/item.asp?ItemID=4722

And came up with this command line that seems to create a file with the same format as the attach query results did with sendMail:

SET @.bcpCommand = "osql -h-1 -w800 /U usrId /P pw /d " + @.dbName + " /Q ""myprocname parm1, parm2"" -o "
SET @.bcpCommand = @.bcpCommand + @.FileName

EXEC master..xp_cmdshell @.bcpCommand

Then just pass @.fileName as the attachment to the cdosys mail procedure. I then use xp_cmdshell to delete the file from the server.

Extended Stored Procedures DB-Lib Alternative

Since DBlib is no longer the suggested method for connecting back to
sql server from an Extended Stored Procedure, has anyone built any
extended stored procedures that use other connection methods like
OLEDB? Has anyone seen links to any sample extended stored procedures
that use something other than db-lib? In particular I am interested
in something that connects back to the database as the user who
invoked the extended stored procedure. I haven't had much luck
finding any.

Also, is there an alternative for the bcp api that is a little more
current and has support for newer datatypes like bigint? We currently
use the bcp api from an extended stored procdure written in C++, but
now need to add bigint support which the bcp api doesn't have.

Thanks for any advice.You can use ODBC or OLEDB, I prefer ODBC because it is lean and mean and I
do not like COM. Both support the full set of data types including BIGINT.

ODBC contains an updated version of the BCP API since SQL Server 7.0 which
also supports all new data types or alternatively you can use the
IRowsetFastload interface if you want to use OLE DB.

There ships an ODBC sample with SQL Server, see "C:\Program Files\Microsoft
SQL Server\80\Tools\DevTools\Samples\ods\xp_odbc", there is no OLE-DB
sample.

GertD@.SQLDev.Net

Please reply only to the newsgroups.
This posting is provided "AS IS" with no warranties, and confers no rights.
You assume all risk for your use.
Copyright SQLDev.Net 1991-2004 All rights reserved.

"Bruce" <sandell@.pacbell.net> wrote in message
news:595024a5.0409171238.10aed173@.posting.google.c om...
> Since DBlib is no longer the suggested method for connecting back to
> sql server from an Extended Stored Procedure, has anyone built any
> extended stored procedures that use other connection methods like
> OLEDB? Has anyone seen links to any sample extended stored procedures
> that use something other than db-lib? In particular I am interested
> in something that connects back to the database as the user who
> invoked the extended stored procedure. I haven't had much luck
> finding any.
> Also, is there an alternative for the bcp api that is a little more
> current and has support for newer datatypes like bigint? We currently
> use the bcp api from an extended stored procdure written in C++, but
> now need to add bigint support which the bcp api doesn't have.
> Thanks for any advice.|||> Since DBlib is no longer the suggested method for connecting back to
> sql server from an Extended Stored Procedure, has anyone built any
> extended stored procedures that use other connection methods like
> OLEDB? Has anyone seen links to any sample extended stored procedures
> that use something other than db-lib? In particular I am interested

ODBC Connection works fine for the loopback in ESP's. Sample
application for the same is provided in the SQL Server Samples|||Thanks very much for the advice. I'll take a look into bcp for odbc.

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

Extended stored procedures and UDP sockets

Hello,
I'm trying this question again; please excuse the repetition.
I have written an extended stored procedure using Visual C++ .Net
(unmanaged). The procedure is intended to send out a UDP multicast message
when new data arrives. The message doesn't seem to be sent.
I have verified that the ESP is getting called correctly (in response to an
INSERT trigger). I have verified that none of the Winsock API procedures
return errors when called from the ESP. I have verified the code that
actually sends the multicast message by running the exact same code from a
console application, where it works fine--including running it when logged i
n
under the account that SQL Server runs under.
There seems to be something unexpectedly different about the environment
that the ESP runs in. I'm at a loss to figure out what it is. Any clues
would be appreciated.
Thanks.
Ed Hoch
GEDDS Manager
Geophysical Institute
University of Alaska FairbanksI'll throw out some thoughts, though I don't have anything definite:
1. Are you initializing the Windows socket library right within the proc?
(I think it's WSAInitialize()). That definitely would need to be done.
2. If you can't get a solution, I know you could set a named Windows event
inside your extended proc (I've done that) and then have another process
waiting on that event and have it send the data gram.
3. Do you have fiber mode turned on in SQL Server? If so, that may affect
threading and sockets (just guessing...)
Mike
"Edward Hoch" <EdwardHoch@.discussions.microsoft.com> wrote in message
news:1A237FAF-EFD9-481B-99F8-6B05CCB3DA35@.microsoft.com...
> Hello,
> I'm trying this question again; please excuse the repetition.
> I have written an extended stored procedure using Visual C++ .Net
> (unmanaged). The procedure is intended to send out a UDP multicast
message
> when new data arrives. The message doesn't seem to be sent.
> I have verified that the ESP is getting called correctly (in response to
an
> INSERT trigger). I have verified that none of the Winsock API procedures
> return errors when called from the ESP. I have verified the code that
> actually sends the multicast message by running the exact same code from a
> console application, where it works fine--including running it when logged
in
> under the account that SQL Server runs under.
> There seems to be something unexpectedly different about the environment
> that the ESP runs in. I'm at a loss to figure out what it is. Any clues
> would be appreciated.
> Thanks.
> Ed Hoch
> --
> GEDDS Manager
> Geophysical Institute
> University of Alaska Fairbanks|||Hi Mike,
Thanks for the reply.
1. I am initializing the socket library with WSAStartup. It seems to work
from the console version of the program, so I think the initialization is
working properly.
2. Named events seem like a possibility. What's a good reference for
those?
3. I am not using the "Windows NT fibers" in my SQL Server. Would it be
more or less likely for the thing to work with fibers enabled?
Thanks again for the reply.
Ed Hoch
"Mike Jansen" wrote:

> I'll throw out some thoughts, though I don't have anything definite:
> 1. Are you initializing the Windows socket library right within the proc?
> (I think it's WSAInitialize()). That definitely would need to be done.
> 2. If you can't get a solution, I know you could set a named Windows event
> inside your extended proc (I've done that) and then have another process
> waiting on that event and have it send the data gram.
> 3. Do you have fiber mode turned on in SQL Server? If so, that may affect
> threading and sockets (just guessing...)
> Mike
> "Edward Hoch" <EdwardHoch@.discussions.microsoft.com> wrote in message
> news:1A237FAF-EFD9-481B-99F8-6B05CCB3DA35@.microsoft.com...
> message
> an
> in
>
>|||> Thanks for the reply.
> 1. I am initializing the socket library with WSAStartup. It seems to
work
> from the console version of the program, so I think the initialization is
> working properly.
WSAStartup, that was it :)

> 2. Named events seem like a possibility. What's a good reference for
> those?
In Windows API look at CreateEvent(), SetEvent(), OpenEvent(). I think
there's even an overview section on synchronization objects. The thing to
be aware of for named objects is that in order for them to work across
process boundaries you need to set up the SECURITY_ATTRIBUTES properly
(unless the other process happens to be running under the same account as
the SQL Server process). The named event won't pass any other context
information.
If you need to pass context information along with triggering an event, you
may want to do something like write out a file and have the process
monitoring a folder rather than an event. There are other options besides
files but file is simple and straightforward.
If you want more information, we can take this offline or to another group
since it's off-topic and can get fairly involved.

> 3. I am not using the "Windows NT fibers" in my SQL Server. Would it be
> more or less likely for the thing to work with fibers enabled?
Like I said, I was just guessing, but I'd guess you might have issues if
fibers were ENABLED a fiber is a "mutant" thread.
Also, perhaps you could try this (though I don't know if it's wise): In
your stored proc WinMain/on load, create a separate thread. Do your sockets
in that thread. That way it's still in the same process but on its own
thread. So your worker thread starts and waits for an item in a context
queue (something you create). When it receives an item in the queue, it
dequeues it and sends a datagram. In your exetended proc, just add items to
the queue. First, I'd do some scanning to see if secondary threads in
extended procs are OK. Regardless, the divantage of this is that its
starting to get complicated and complicated things mess up more often and
messing up inside the process space of SQL Server isn't the greatest thing.
So even if secondary threads are OK, BE VERY CAREFUL.
Mike|||What is the service account of SQL Server? Start the SQL Server service from
the command line, and execute the XP, see if that makes a difference.
GertD@.SQLDev.Net
Please reply only to the newsgroups.
This posting is provided "AS IS" with no warranties, and confers no rights.
You assume all risk for your use.
Copyright SQLDev.Net 1991-2005 All rights reserved.
"Edward Hoch" <EdwardHoch@.discussions.microsoft.com> wrote in message
news:1A237FAF-EFD9-481B-99F8-6B05CCB3DA35@.microsoft.com...
> Hello,
> I'm trying this question again; please excuse the repetition.
> I have written an extended stored procedure using Visual C++ .Net
> (unmanaged). The procedure is intended to send out a UDP multicast
> message
> when new data arrives. The message doesn't seem to be sent.
> I have verified that the ESP is getting called correctly (in response to
> an
> INSERT trigger). I have verified that none of the Winsock API procedures
> return errors when called from the ESP. I have verified the code that
> actually sends the multicast message by running the exact same code from a
> console application, where it works fine--including running it when logged
> in
> under the account that SQL Server runs under.
> There seems to be something unexpectedly different about the environment
> that the ESP runs in. I'm at a loss to figure out what it is. Any clues
> would be appreciated.
> Thanks.
> Ed Hoch
> --
> GEDDS Manager
> Geophysical Institute
> University of Alaska Fairbanks

Extended Stored Procedures 7.0 - 2000

I have a problem with passing parameters into an extended stored procedure in sql 2000 that was not present in sql 7.0.

I pass in a parameter of type varchar(8000) but sql 2000 truncates this value to 255 characters.

I was using srv_paramdata(sproc,1) for example to get the pertinent data. Microsoft says that srv_paramdata has been superceded by srv_paraminfo, but this function is crashing my dll when I run it....

BYTE bType;
unsigned long cbMaxLen;
unsigned long cbActualLen;
BOOL fNull;
BYTE data;

// Use srv_paraminfo to get data type and length information.
srv_paraminfo(sproc, 2, &bType, &cbMaxLen, &cbActualLen,&data, &fNull);

Any ideas?

This worked in sql 7.0.

wsprintf(string,"%s",(const char*) srv_paramdata(sproc,1));

Umm help appreciated.

WintermuteUmm actual guys... thanks to anyone who has looked to help me out, but I think I have (*this).sorted->muchos[gracias++];

umm in keeping with Open Source Software paradigms and stuff if anyone is curious

PBYTE*data;
BYTE type;
unsigned long Maxlen;
unsigned long Reallen;
int nParams;
BOOL boolnull;
char head_descriptor[24];
FILE*file;

nParams=srv_rpcparams(sproc);


data=new PBYTE[1];
if(data==NULL)
{
ServerErrorMsg(sproc,"Was unable to allocate the requisite memory for this data operation");
return -1;
};
memset(data,0,nParams*sizeof(PBYTE));


srv_paraminfo(sproc,2,&type,&Maxlen,&Reallen,NULL,&boolnull);

sprintf(head_descriptor,"Parameter 2: Input");
srv_describe(sproc,2,head_descriptor,SRV_NULLTERM, type,Reallen,type,Reallen,NULL);

if(boolnull==0)
{
data[0]=(unsigned char*)malloc(Reallen);
if(data[0]==NULL)
{
ServerErrorMsg(sproc,"Unable to allocate memory for this variable!");
delete data;
return -1;
};

srv_paraminfo(sproc,2,&type,&Maxlen,&Reallen,data[0],&boolnull);
}
else
{
ServerErrorMsg(sproc,"There Seems to be no data present for parameter 2");
return -1;
};

file=fopen("C:/bod.txt","a+");
if(file==NULL)
{
ServerErrorMsg(sproc,"Unable to access the specified filename for file input, Please check the filename and try again!");
return -1;
};

fwrite(data[0],Reallen,1,file);
fclose(file);


return 0;
};

Regards
Wintermute.sql

Extended Stored Procedures -> loading linked files

Hello everybody

I actually wrote a stored procedure (in xp_wrapper.dll) that is using a dll (original.dll) which uses a license file (no file extension)... clear? :)

Anyway.

All the required files are placed in the BINN dir of the server.

The problem is now, that original.dll can't find it's license file. It seems, that this file was not load by SQL Server.

How can I load this file into SQL Server's heap?

Yours
MikeYou need to checkout the Win32 level LoadLibrary() call to explicitly load the DLL. You will need to explicitly FreeLibrary the DLL before you exit from the xp call.

Extended Stored Procedures

Hi !
Please advise which libs and include files are required
to compile extended stored procedure file for SQL Server 2000
in VC++.
Thanks in advance:From SQL 2000 BOL under "extended stored procedures, creating":
To create an extended stored procedure DLL by using Microsoft Visual C++
Create a new project of type Win32 Dynamic Link Library.
Set the directory for include files and library files to C:\Program
Files\Microsoft SQL Server\80\Tools\DevTools\Include and C:\Program
Files\Microsoft SQL Server\80\Tools\DevTools\Lib, respectively.
On the Tools menu, click Options.
In the Options dialog box, click the Directories tab and set the directory
for include files and library files.
On the Project menu, click Settings.
In the Project Settings dialog box, click the Link tab. Click the General
category, and then add opends60.lib to object/library modules.
Add source files (.c, .cpp, and .rc files, and so on) to your project.
Compile and link your project.
Regards
Mike
"IMRAN SAROIA" wrote:

> Hi !
> Please advise which libs and include files are required
> to compile extended stored procedure file for SQL Server 2000
> in VC++.
> Thanks in advance:
>
>

Extended stored procedure?

I noticed that there is something in master database called
Extended stored procedure which can be dlls? what's this? How can we make
our own sps a dll and put it somewhere like this?
Thankshttp://www.codeproject.com/database/extended_sp.asp
"Ray5531" <RayAll@.microsft.com> wrote in message
news:%23984aPOTFHA.612@.TK2MSFTNGP12.phx.gbl...
>I noticed that there is something in master database called
> Extended stored procedure which can be dlls? what's this? How can we make
> our own sps a dll and put it somewhere like this?
>
> Thanks
>|||Whoa, you really don't want to venture there. Xp runs as in-proc thus a
simple mistake in your custom xp can take the entire sqlserver down.
Anyway, here is some read.
http://msdn.microsoft.com/library/e...des_07_9rxv.asp
http://msdn.microsoft.com/library/e...con_01_22sz.asp
-oj
"Ray5531" <RayAll@.microsft.com> wrote in message
news:%23984aPOTFHA.612@.TK2MSFTNGP12.phx.gbl...
>I noticed that there is something in master database called
> Extended stored procedure which can be dlls? what's this? How can we make
> our own sps a dll and put it somewhere like this?
>
> Thanks
>|||Do they really have to be in Master Database only?
I don't know C++,is there another way of making an extended sp? like using
C#?
Thanks
"Michael C#" <howsa@.boutdat.com> wrote in message
news:%23Oc2HSOTFHA.2304@.tk2msftngp13.phx.gbl...
> http://www.codeproject.com/database/extended_sp.asp
>
> "Ray5531" <RayAll@.microsft.com> wrote in message
> news:%23984aPOTFHA.612@.TK2MSFTNGP12.phx.gbl...
>|||Not in managed code, no. AFAIK, SQL 2K5 will allow hosting of managed code.
I would either: 1) Write whatever you're trying to do as an external app and
run it separately from SQL Server, or 2) Wait for SQL 2K5.
"Ray5531" <RayAll@.microsft.com> wrote in message
news:%23ECPaUOTFHA.584@.TK2MSFTNGP15.phx.gbl...
> Do they really have to be in Master Database only?
> I don't know C++,is there another way of making an extended sp? like using
> C#?
> Thanks
> "Michael C#" <howsa@.boutdat.com> wrote in message
> news:%23Oc2HSOTFHA.2304@.tk2msftngp13.phx.gbl...
>|||Can I write my own sps as dlls in 2005 with managed code ?
Thanks
"Michael C#" <howsa@.boutdat.com> wrote in message
news:u1iDgeOTFHA.3216@.TK2MSFTNGP10.phx.gbl...
> Not in managed code, no. AFAIK, SQL 2K5 will allow hosting of managed
> code. I would either: 1) Write whatever you're trying to do as an external
> app and run it separately from SQL Server, or 2) Wait for SQL 2K5.
> "Ray5531" <RayAll@.microsft.com> wrote in message
> news:%23ECPaUOTFHA.584@.TK2MSFTNGP15.phx.gbl...
>|||> Do they really have to be in Master Database only?
Yes.

> I don't know C++,is there another way of making an extended sp? like using C#?[/co
lor]
Not managed code. Not classic VB (as it creates COM DLLs, not classic DLLs).
Only C, C++ or Delphi.
Another option is to write a COM object and use SP_OACreate etc. to use that
COM object.
--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Ray5531" <RayAll@.microsft.com> wrote in message news:%23ECPaUOTFHA.584@.TK2MSFTNGP15.phx.gb
l...
> Do they really have to be in Master Database only?
> I don't know C++,is there another way of making an extended sp? like using
C#?
> Thanks
> "Michael C#" <howsa@.boutdat.com> wrote in message news:%23Oc2HSOTFHA.2304@.
tk2msftngp13.phx.gbl...
>|||I can't speak to extended sp's on 2K5, but my understanding is that you'll
be able to create SP's, functions, triggers and data types in managed code
that runs on SQL 2K5.
Here's a link to some MS Marketing stuff:
http://msdn.microsoft.com/msdntv/ep...>
manifest.xml
"Ray5531" <RayAll@.microsft.com> wrote in message
news:uIQ%23wxOTFHA.2096@.TK2MSFTNGP14.phx.gbl...
> Can I write my own sps as dlls in 2005 with managed code ?
> Thanks
> "Michael C#" <howsa@.boutdat.com> wrote in message
> news:u1iDgeOTFHA.3216@.TK2MSFTNGP10.phx.gbl...
>|||The official word regarding calling a .NET component with sp_OA* is "not
supported".
http://support.microsoft.com/kb/322884
However, David Browne has some work around...
http://tinyurl.com/4ur72
-oj
"Ray5531" <RayAll@.microsft.com> wrote in message
news:uIQ%23wxOTFHA.2096@.TK2MSFTNGP14.phx.gbl...
> Can I write my own sps as dlls in 2005 with managed code ?
> Thanks
> "Michael C#" <howsa@.boutdat.com> wrote in message
> news:u1iDgeOTFHA.3216@.TK2MSFTNGP10.phx.gbl...
>

Extended Stored Procedure: Loopback connection

Hi
How can I create a loopback connection? I havn't a DSN and want make a
connection to the SQL server in my Extended Stored Procedure. As I see I can
read the user and the password in my Extended Stored Procedure, but i havn't
the DSN. Can I make a (local) connection without a DSN?
I want to communicate with the SQL server in my extended stored procedure
via ODBC (SQLConnect, SQLExecDirect, SQLBindCol and so on).
A small code sample would be great.
Thanks
HansSQL Server ships a sample exactly showing this:
C:\Program Files\Microsoft SQL
Server\80\Tools\DevTools\Samples\ods\unz
ip_ods.exe
Contains
C:\Program Files\Microsoft SQL Server\80\Tools\DevTools\Samples\ods\xp_
odbc
/ ****************************************
*******************************
Copyright (c) 2000, Microsoft Corporation
All Rights Reserved.
****************************************
*******************************/
// This is an example of an extended procedure DLL built with Open Data
// Services. The functions within the DLL can be invoked by using the
extended
// stored procedures support in SQL Server. To register the functions
// and allow all users to use them run the ISQL script XP_ODBC.SQL.
//
// For further information on Open Data Services refer to the Microsoft Open
// Data Services Programmer's Reference.
//
// The extended procedures implemented in this DLL is:
//
// XP_GETTABLE_ODBC -- Used to show the creation of a new connection to
// SQL Server using ODBC that is bound to the initial client connection
#include <windows.h>
#include <tchar.h>
#include <string.h>
#include <sql.h>
#include <sqlext.h>
#include <odbcss.h>
#include <srv.h>
// Miscellaneous defines.
#define XP_NOERROR 0
#define XP_ERROR 1
// Extended procedure error codes.
#define SRV_MAXERROR 50000
#define GETTABLE_ERROR SRV_MAXERROR + 1
#define REMOTE_FAIL 4002
void handle_odbc_err(PSTR szODBCApi,
SQLRETURN sret,
DBINT msgnum,
SQLHANDLE herror,
SQLSMALLINT htype,
SRV_PROC* srvproc);
// It is highly recommended that all Microsoft SQL Server (7.0
// and greater) extended stored procedure DLLs implement and export
// __GetXpVersion. For more information see SQL Server
// Books Online
ULONG __GetXpVersion()
{
return ODS_VERSION;
}
// XP_GETTABLE_ODBC
// Returns the result of the SQL statement
// select * from <szTable>
//
// Parameters:
// srvproc - the handle to the client connection that
// got the SRV_CONNECT.
//
// Returns:
// XP_NOERROR
// XP_ERROR
//
// Side Effects:
// Returns messages and/or a result set to client.
RETCODE xp_gettable_odbc(srvproc)
SRV_PROC *srvproc;
{
HENV henv = SQL_NULL_HENV;
HDBC hdbc = SQL_NULL_HDBC;
HSTMT hstmt = SQL_NULL_HSTMT;
SQLRETURN sret;
RETCODE rc;
char acBindToken[256];
// ODBC column attributes.
TCHAR acColumnName[MAXNAME];
SQLINTEGER cbColData;
SQLSMALLINT eSQLType;
SQLINTEGER iNumAttr;
SQLSMALLINT cbAttr; // pointer to storage for descriptor info
PBYTE* ppData = NULL;
SQLINTEGER* pIndicators = NULL;
DBINT rows = 0L; // number of rows sent
PTSTR szDSN = _T("local"); // for integrated security to work you need to
// specify a local server in the ODBC setting
// in the Control Panel in Windows
int bImpersonated;
TCHAR acUID[MAXNAME];
TCHAR acPWD[MAXNAME];
int nParams;
DBINT paramtype;
TCHAR szTable[MAXNAME * 3]; // database.owner.table
TCHAR szExec[128 + (MAXNAME * 3)];
SQLSMALLINT nCols;
SQLSMALLINT nCol;
RETCODE rcXP = XP_ERROR; // Assume failure until shown otherwise.
// Get number of parameters.
nParams = srv_rpcparams(srvproc);
// Check number of parameters
if (nParams != 1) {
// Send error message and return
srv_sendmsg(srvproc, SRV_MSG_ERROR, GETTABLE_ERROR, SRV_INFO, (DBTINYINT)0,
NULL, 0, 0, "Error executing extended stored procedure: Invalid Parameter",
SRV_NULLTERM);
// A SRV_DONE_MORE instead of a SRV_DONE_FINAL must complete the
// result set of an Extended Stored Procedure.
srv_senddone(srvproc, (SRV_DONE_ERROR | SRV_DONE_MORE), 0, 0);
return(XP_ERROR);
}
// If parameter is not varchar (should be a table name), send an
// error and return.
paramtype = srv_paramtype(srvproc, nParams);
if (paramtype != SRVVARCHAR) {
srv_sendmsg(srvproc, SRV_MSG_ERROR, GETTABLE_ERROR, SRV_INFO, (DBTINYINT)0,
NULL, 0, 0,
"Error executing extended stored procedure: Invalid Parameter Type",
SRV_NULLTERM);
// A SRV_DONE_MORE instead of a SRV_DONE_FINAL must complete the
// result set of an Extended Stored Procedure.
srv_senddone(srvproc, (SRV_DONE_ERROR | SRV_DONE_MORE), 0, 0);
return(XP_ERROR);
}
// Terminate parameter string with NULL.
memcpy(szTable, srv_paramdata(srvproc, 1),
srv_paramlen(srvproc, 1));
szTable[srv_paramlen(srvproc, 1)] = '\0';
// Allocate an ODBC environment handle
sret = SQLAllocHandle(SQL_HANDLE_ENV, NULL, &henv);
if (sret != SQL_SUCCESS) {
handle_odbc_err("SQLAllocHandle:Env",
sret,
(DBINT) REMOTE_FAIL,
henv,
SQL_HANDLE_ENV,
srvproc);
return(XP_ERROR);
}
SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3,
SQL_IS_INTEGER);
// Allocate an ODBC connection handle
sret = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);
if (sret != SQL_SUCCESS) {
handle_odbc_err("SQLAllocHandle:Dbc",
sret,
(DBINT)REMOTE_FAIL,
henv,
SQL_HANDLE_ENV,
srvproc);
SQLFreeHandle(SQL_HANDLE_ENV, henv);
return(XP_ERROR);
}
// Check for integrated security.
if (strcmp(srv_pfield(srvproc, SRV_LSECURE, (int *)NULL), "TRUE") == 0)
3;
// Client has accessed using some form of integrated security
// Impersonate client and set SQL_INTEGRATED_SECURITY option
bImpersonated = srv_impersonate_client(srvproc);
// Connect to DSN using integrated security
SQLSetConnectAttr(hdbc, SQL_INTEGRATED_SECURITY,
(SQLPOINTER) SQL_IS_ON, SQL_IS_INTEGER);
_tcscpy(acUID, _T(""));
_tcscpy(acPWD, _T(""));
}
else {
// Client used standard login. Set the user name and password.
#ifdef UNICODE
MultiByteToWideChar(CP_ACP, 0, srv_pfield(srvproc, SRV_USER, NULL),
-1, acUID, MAXNAME);
MultiByteToWideChar(CP_ACP, 0, srv_pfield(srvproc, SRV_PWD, NULL),
-1, acPWD, MAXNAME);
#else
strncpy(acUID, srv_pfield(srvproc, SRV_USER, NULL),
MAXNAME);
strncpy(acPWD, srv_pfield(srvproc, SRV_PWD, NULL),
MAXNAME);
#endif
}
if (!SQL_SUCCEEDED(
sret = SQLConnect(hdbc, (SQLTCHAR*) szDSN, SQL_NTS,
(SQLTCHAR*) acUID, SQL_NTS, (SQLTCHAR*) acPWD, SQL_NTS)
)) {
handle_odbc_err("SQLConnect",
sret,
(DBINT)REMOTE_FAIL,
hdbc,
SQL_HANDLE_DBC,
srvproc);
goto SAFE_EXIT;
}
// Process data after successful connection
sret = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);
if (sret != SQL_SUCCESS) {
handle_odbc_err("SQLAllocHandle",
sret,
(DBINT)REMOTE_FAIL,
hdbc,
SQL_HANDLE_DBC,
srvproc);
return(XP_ERROR);
}
// Get the client session token...
rc = srv_getbindtoken(srvproc, acBindToken);
if (rc == FAIL) {
srv_sendmsg(srvproc,
SRV_MSG_ERROR,
GETTABLE_ERROR,
SRV_INFO,
(DBTINYINT) 0,
NULL,
0,
0,
"Error with srv_getbindtoken",
SRV_NULLTERM);
srv_senddone(srvproc, (SRV_DONE_ERROR | SRV_DONE_MORE), 0, 0);
return(XP_ERROR);
}
// ...bind it as an ODBC parameter for the stored procedure call...
_tcscpy(szExec, _T("{call sp_bindsession(?)}"));
sret = SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR,
SQL_VARCHAR, 255, 0, acBindToken, 256, NULL);
if (sret != SQL_SUCCESS) {
handle_odbc_err("SQLBindParameter",
sret,
(DBINT)REMOTE_FAIL,
hstmt,
SQL_HANDLE_STMT,
srvproc);
return(XP_ERROR);
}
// ...and, using sp_bindsession, bind our session to the client's
// session so that we share transaction space.
sret = SQLExecDirect(hstmt, (SQLTCHAR*) szExec, SQL_NTS);
if (!((sret == SQL_SUCCESS) ||(sret == SQL_SUCCESS_WITH_INFO))) {
handle_odbc_err("SQLExecDirect",
sret,
(DBINT) GETTABLE_ERROR,
hstmt,
SQL_HANDLE_STMT,
srvproc);
return(XP_ERROR);
}
SQLFreeStmt(hstmt, SQL_RESET_PARAMS);
// SELECT the result set.
_tcscpy(szExec, _T("SELECT * FROM "));
_tcscat(szExec, szTable);
sret = SQLExecDirect(hstmt, (SQLTCHAR*) szExec, SQL_NTS);
if (sret != SQL_SUCCESS) {
handle_odbc_err("SQLExecDirect",
sret,
(DBINT) GETTABLE_ERROR,
hstmt,
SQL_HANDLE_STMT,
srvproc);
return(XP_ERROR);
}
// Get the number of columns in the ODBC result set.
SQLNumResultCols(hstmt, &nCols);
ppData = (PBYTE*) malloc(nCols * sizeof(PBYTE));
pIndicators = malloc(nCols * sizeof(SQLINTEGER));
if (ppData == NULL || pIndicators == NULL)
goto SAFE_EXIT;
// Build the column description for this results set.
for (nCol = 0; nCol < nCols; nCol++) {
// Get the column name, length and data type.
SQLColAttribute(hstmt,
(SQLSMALLINT) (nCol + 1),
SQL_DESC_NAME,
(SQLTCHAR*) acColumnName, // returned column name
MAXNAME, // max length of rgbDesc buffer
&cbAttr, // number of bytes returned in rgbDesc
&iNumAttr);
SQLColAttribute(hstmt,
(SQLSMALLINT) (nCol + 1),
SQL_DESC_OCTET_LENGTH,
NULL,
0,
NULL,
&cbColData);
// Get the column's SQL Server data type, then reset the length
// of the data retrieved as required.
SQLColAttribute(hstmt,
(SQLSMALLINT) (nCol + 1),
SQL_CA_SS_COLUMN_SSTYPE,
NULL,
0,
NULL,
&eSQLType);
// Over-write the column length returned by ODBC with the correct value
// to be used by ODS
switch( eSQLType ) {
case SQLMONEYN:
case SQLMONEY:
cbColData = sizeof(DBMONEY);
break;
case SQLDATETIMN:
case SQLDATETIME:
cbColData = sizeof(DBDATETIME);
break;
case SQLNUMERIC:
case SQLDECIMAL:
cbColData = sizeof(DBNUMERIC);
break;
case SQLMONEY4:
cbColData = sizeof(DBMONEY4);
break;
case SQLDATETIM4: //smalldatetime
cbColData = sizeof(DBDATETIM4);
break;
}
// Allocate memory for row data.
if ((ppData[nCol] = (PBYTE) malloc(cbColData)) == NULL)
goto SAFE_EXIT;
memset(ppData[nCol], 0, cbColData);
// Bind column
SQLBindCol(hstmt,
(SQLSMALLINT) (nCol + 1),
SQL_C_BINARY, // No data conversion.
ppData[nCol],
cbColData,
&(pIndicators[nCol]));
// Prepare structure that will be sent via ODS back to
// the caller of the extended procedure
srv_describe(srvproc,
nCol + 1,
acColumnName,
SRV_NULLTERM,
eSQLType, // Dest data type.
(DBINT) cbColData, // Dest data length.
eSQLType, // Source data type.
(DBINT) cbColData, // Source data length.
(PBYTE) NULL);
}
// Initialize the row counter
rows = 0;
// Get each row of data from ODBC until there are no more rows
while((sret = SQLFetch(hstmt)) != SQL_NO_DATA_FOUND) {
if (!SQL_SUCCEEDED(sret)) {
handle_odbc_err("SQLFetch",
sret,
(DBINT) GETTABLE_ERROR,
hstmt,
SQL_HANDLE_STMT,
srvproc);
goto SAFE_EXIT;
}
// For each data field in the current row, fill the structure
// that will be sent back to the caller.
for (nCol = 0; nCol < nCols; nCol++) {
cbColData = (pIndicators[nCol] == SQL_NULL_DATA ?
0 : pIndicators[nCol]);
srv_setcollen(srvproc, nCol+1, (int) cbColData);
srv_setcoldata(srvproc, nCol+1, ppData[nCol]);
}
// Send the data row back to SQL Server via ODS.
if (srv_sendrow(srvproc) == SUCCEED)
rows++;
}
if (rows > 0)
srv_senddone(srvproc, SRV_DONE_MORE | SRV_DONE_COUNT, (DBUSMALLINT)0, rows);
else
srv_senddone(srvproc, SRV_DONE_MORE, (DBUSMALLINT)0, (DBINT)0);
// We got here successfully, let the client know.
rcXP = XP_NOERROR;
SAFE_EXIT:
// Free the data buffers.
if (ppData != NULL)
{
for (nCol = 0; nCol < nCols; nCol++)
free(ppData[nCol]);
free(ppData);
}
if (pIndicators != NULL)
free(pIndicators);
// Free handles.
if (hstmt != SQL_NULL_HSTMT)
SQLFreeStmt(hstmt, SQL_DROP);
if (hdbc != SQL_NULL_HDBC)
{
SQLDisconnect(hdbc);
SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
}
if (henv != SQL_NULL_HENV)
SQLFreeEnv(henv);
// Revert back to SQL Server's user account.
if( bImpersonated )
srv_revert_to_self(srvproc);
return (rcXP);
}
// HANDLE_ODBC_ERR
// This routine is called to send messages to clients when an ODBC
// function returns what could be considered an error (e.g., SQL_ERROR,
// SQL_INVALID_HANDLE).
//
// Parameters:
// szODBCApi - The name of the failing function.
// srODBAPI - The SQLRETURN of the failing function.
// msgnum - The ODS user message code.
// herror - The ODBC handle involved in the error.
// htype - The ODBC handle type.
// srvproc - Contains additional client information.
//
// Returns:
// none
//
void handle_odbc_err(PSTR szODBCApi,
SQLRETURN sret,
DBINT msgnum,
SQLHANDLE herror,
SQLSMALLINT htype,
SRV_PROC* srvproc)
{
SQLTCHAR szErrorMsg[SQL_MAX_MESSAGE_LENGTH + 1];
SQLSMALLINT cbErrorMsg;
SQLSMALLINT nRec = 1;
// If sret is SQL_SUCCESS, return without doing anything
if (sret == SQL_SUCCESS)
return;
while (
SQLGetDiagField(htype, herror, nRec++, SQL_DIAG_MESSAGE_TEXT,
szErrorMsg, SQL_MAX_MESSAGE_LENGTH, &cbErrorMsg)
== SQL_SUCCESS)
{
// If sret is SUCCESS_WITH_INFO, send as "message" (severity
// <= 10, we use zero), else send to client as "error"
// (severity > 10, we use 11).
srv_sendmsg(srvproc,
SRV_MSG_INFO,
msgnum,
(DBTINYINT) (sret == SQL_SUCCESS_WITH_INFO ? 0 : 11),
(DBTINYINT) 1,
NULL,
0,
0,
szErrorMsg,
SRV_NULLTERM);
}
}
"Hans Stoessel" <hstoessel.list@.pm-medici.ch> wrote in message
news:%23Vtf%23S3YGHA.3704@.TK2MSFTNGP03.phx.gbl...
> Hi
> How can I create a loopback connection? I havn't a DSN and want make a
> connection to the SQL server in my Extended Stored Procedure. As I see I
> can
> read the user and the password in my Extended Stored Procedure, but i
> havn't
> the DSN. Can I make a (local) connection without a DSN?
> I want to communicate with the SQL server in my extended stored procedure
> via ODBC (SQLConnect, SQLExecDirect, SQLBindCol and so on).
> A small code sample would be great.
> Thanks
> Hans
>

Extended Stored Procedure: Get the current db of the client

Hi
Is there a way to get the current database of the client who calls my
Extended Stored Procedure?
I have written a DLL in Visual Studion 2005 for the SQL server 2003 in C/C++
using the functions srv_*.
Thanks.
HansWhat version of SQL Server?
It's a limitation of extended stored procedure programming
with SQL Server 2000. Some have tried using svr_rpcdb but it
will generally just return master as the database name. And
it's no longer supported.
-Sue
On Mon, 8 May 2006 14:41:59 +0200, "Hans Stoessel"
<hstoessel.list@.pm-medici.ch> wrote:

>Hi
>Is there a way to get the current database of the client who calls my
>Extended Stored Procedure?
>I have written a DLL in Visual Studion 2005 for the SQL server 2003 in C/C+
+
>using the functions srv_*.
>Thanks.
>Hans
>|||This never worked correctly, this is not way you can get the database
context from within an XP, easiest work around is to use a wrapper SP that
passes the db_name() or db_id() as a parameter.
In general using wrapper SP's is a good practice for doing parameter
validation, and meta data exposure since XP's do not emit the parameter
signatures.
GertD@.SQLDev.Net
"Sue Hoegemeier" <Sue_H@.nomail.please> wrote in message
news:feuv521gpm893g6hfi4aja0vpp8vguiun4@.
4ax.com...
> What version of SQL Server?
> It's a limitation of extended stored procedure programming
> with SQL Server 2000. Some have tried using svr_rpcdb but it
> will generally just return master as the database name. And
> it's no longer supported.
> -Sue
> On Mon, 8 May 2006 14:41:59 +0200, "Hans Stoessel"
> <hstoessel.list@.pm-medici.ch> wrote:
>
>|||Works for SP's, might work with XP's as well:
1. Prefix the name with "sp_"
2. Mark it as a system object with sp_MS_MarkSystemObject
This causes the SP to run under the context of the database it was called
from, not the master database where it resides. At the least, you can put
an SP wrapper in the master DB for the XP, and pass in the db_name() as a
parameter to the XP and it will have the correct database context (not
"master").
"Gert E.R. Drapers" <GertD@.SQLDev@.Net> wrote in message
news:%23ZtUJnzcGHA.3632@.TK2MSFTNGP05.phx.gbl...
> This never worked correctly, this is not way you can get the database
> context from within an XP, easiest work around is to use a wrapper SP that
> passes the db_name() or db_id() as a parameter.
> In general using wrapper SP's is a good practice for doing parameter
> validation, and meta data exposure since XP's do not emit the parameter
> signatures.
> GertD@.SQLDev.Net
>
> "Sue Hoegemeier" <Sue_H@.nomail.please> wrote in message
> news:feuv521gpm893g6hfi4aja0vpp8vguiun4@.
4ax.com...
>|||Does not matter, an XP does not have a call to retrieve the database
context.
GertD@.SQLDev.Net
"Mike C#" <xxx@.yyy.com> wrote in message news:wzR8g.505$Ut2.124@.fe09.lga...
> Works for SP's, might work with XP's as well:
> 1. Prefix the name with "sp_"
> 2. Mark it as a system object with sp_MS_MarkSystemObject
> This causes the SP to run under the context of the database it was called
> from, not the master database where it resides. At the least, you can put
> an SP wrapper in the master DB for the XP, and pass in the db_name() as a
> parameter to the XP and it will have the correct database context (not
> "master").
>
> "Gert E.R. Drapers" <GertD@.SQLDev@.Net> wrote in message
> news:%23ZtUJnzcGHA.3632@.TK2MSFTNGP05.phx.gbl...
>|||DBLIB, dbname() function.
http://msdn.microsoft.com/library/d...br />
2gtz.asp
enjoy
"Gert E.R. Drapers" <GertD@.SQLDev@.Net> wrote in message
news:u8i0W6WdGHA.4720@.TK2MSFTNGP03.phx.gbl...
> Does not matter, an XP does not have a call to retrieve the database
> context.
> GertD@.SQLDev.Net
> "Mike C#" <xxx@.yyy.com> wrote in message
> news:wzR8g.505$Ut2.124@.fe09.lga...
>|||No, because then you need to connect first! So what database do you
establish your connection to?
Please don't answer try to answer questions you do not know the answer to.
-GertD
"Mike C#" <xxx@.yyy.com> wrote in message news:Ga99g.60$Id.19@.fe10.lga...
> DBLIB, dbname() function.
> http://msdn.microsoft.com/library/d... />
z_2gtz.asp
> enjoy
> "Gert E.R. Drapers" <GertD@.SQLDev@.Net> wrote in message
> news:u8i0W6WdGHA.4720@.TK2MSFTNGP03.phx.gbl...
>|||And you plan to what? Put the same "wrapper" stored procedure in every
single database on a server?
Don't be a dick Gertrude.
"Gert E.R. Drapers" <GertD@.SQLDev@.Net> wrote in message
news:Ou6TvyjdGHA.3632@.TK2MSFTNGP05.phx.gbl...
> No, because then you need to connect first! So what database do you
> establish your connection to?
> Please don't answer try to answer questions you do not know the answer to.
> -GertD
> "Mike C#" <xxx@.yyy.com> wrote in message news:Ga99g.60$Id.19@.fe10.lga...
>|||underprocessable|||"Gert E.R. Drapers" wrote:

> No, you are incorrect; for an extended stored procedure you have to pass i
n
> the database context as a parameter if you need it, that is the only thing
> that works. Did you ever write an extended stored procedure?
I have written several, several, several extended stored procedures. In
fact, I just publicly released about 3 dozen that cover everything from AES,
Blowfish, Twofish, DES and TripleDES encryption to regular expressions to
recursively reading a local subdirectory listing.
In fact, here's a little experiment for you extended procedure maestro: Put
this regular stored procedure in the Master database:
CREATE PROCEDURE dbo.Test1
AS
SELECT db_Name()
GO
Now run it from within the Model database. Or the Northwind database. What
database name comes up? Master, that's what. According to your solution,
you need to recreate this exact same stored procedure in every single
database you own in order to get the current database context out of it.
As I said: changing the name to "sp_..." and marking it as a system object
will allow you to use JUST ONE copy of the stored procedure in Master. It
will run in the context of the CURRENT DATABASE, no matter what database you
invoke it from. But I'm sure you're well aware of that.

> Besides that it does not make sense to call the DB-Lib function dbname()
> untill you established a loopback connection over DB-Library, which would
> default to the default database for the user which is not the same as the
> database context. See the attached example which shows this behavior.
And that's all well and good. I was simply pointing out some things that
might be tried, and you pointed out that it wouldn't work in your own little
snide way.

> The srv_rpc* class methods in the OPENDS60.LIB file are obsolete since the
y
> are gateway calls and not longer supported; srv_rpcdb() only gave you a
> database context when you where a remote procedure, which is something
> different than an extended stored procedure, so that is not giving you wan
t
> you want either.
I know srv_rpcdb doesn't work, and didn't suggest it as a solution. I'm
sure whoever didn't know that will be happy to hear it from you, however.

> So Mike C#, the ONLY solution is to pass it in as a parameter!
Which is fine, and perfectly acceptable. The difference is simply this, if
you refer back to my original post: Your method requires the same stored
procedure be copied to all 28 of my databases. Alternatively I can put a
single copy in the Master database and be done with it.

> BTW: Next time you are calling somebody names you might want to check your
> facts before replying an making a fool out of yourself.
BTW: You should check your facts before you accuse someone of not having
any experience in your little domain over there before making a fool of
yourself.
http://www.sqlservercentral.com/col...oolkitpart1.asp
http://www.sqlservercentral.com/col...oolkitpart2.asp
http://www.sqlservercentral.com/col...oolkitpart3.asp
http://www.sqlservercentral.com/col...oolkitpart4.asp
Of course I'd love an opportunity to learn at the master's feet. So where
does Master Gert keep his extended procedures, that I may immerse myself in
the knowledge to be gained?sql

Extended stored procedure, performance?

"Cesare" <cvairetti@.mcgestioni.it> wrote in message
news:et2MIqvjGHA.4304@.TK2MSFTNGP03.phx.gbl...
> Hi everybody,
> I should begin to write a DLL library for Sql2000 server.
> The functions I like to implement are mathematical functions, like
> standard
> deviation, and similar, nothing really complex. Often I have to use more
> then one standard deviation inside the sama function, using subset of a
> record set.
> Of course I can use sql2000, that implemets standard deviation and basic
> mathematical function, so the question is: is it opportune to write a DDL
> to
> improve performance, or is it worse, or just the same?
>
Extended stored procedures are so dangerous to the stability of the database
server that they should be used very, very carefully.
In SQL 2005 CLR integration provides a safe way to extent the SQL engine
with custom calculations.
DavidHi everybody,
I should begin to write a DLL library for Sql2000 server.
The functions I like to implement are mathematical functions, like standard
deviation, and similar, nothing really complex. Often I have to use more
then one standard deviation inside the sama function, using subset of a
record set.
Of course I can use sql2000, that implemets standard deviation and basic
mathematical function, so the question is: is it opportune to write a DDL to
improve performance, or is it worse, or just the same?
thanks a lot for any kindly advice
cesare|||"Cesare" <cvairetti@.mcgestioni.it> wrote in message
news:et2MIqvjGHA.4304@.TK2MSFTNGP03.phx.gbl...
> Hi everybody,
> I should begin to write a DLL library for Sql2000 server.
> The functions I like to implement are mathematical functions, like
> standard
> deviation, and similar, nothing really complex. Often I have to use more
> then one standard deviation inside the sama function, using subset of a
> record set.
> Of course I can use sql2000, that implemets standard deviation and basic
> mathematical function, so the question is: is it opportune to write a DDL
> to
> improve performance, or is it worse, or just the same?
>
Extended stored procedures are so dangerous to the stability of the database
server that they should be used very, very carefully.
In SQL 2005 CLR integration provides a safe way to extent the SQL engine
with custom calculations.
David

Extended stored procedure, performance?

Hi everybody,
I should begin to write a DLL library for Sql2000 server.
The functions I like to implement are mathematical functions, like standard
deviation, and similar, nothing really complex. Often I have to use more
then one standard deviation inside the sama function, using subset of a
record set.
Of course I can use sql2000, that implemets standard deviation and basic
mathematical function, so the question is: is it opportune to write a DDL to
improve performance, or is it worse, or just the same?
thanks a lot for any kindly advice
cesare"Cesare" <cvairetti@.mcgestioni.it> wrote in message
news:et2MIqvjGHA.4304@.TK2MSFTNGP03.phx.gbl...
> Hi everybody,
> I should begin to write a DLL library for Sql2000 server.
> The functions I like to implement are mathematical functions, like
> standard
> deviation, and similar, nothing really complex. Often I have to use more
> then one standard deviation inside the sama function, using subset of a
> record set.
> Of course I can use sql2000, that implemets standard deviation and basic
> mathematical function, so the question is: is it opportune to write a DDL
> to
> improve performance, or is it worse, or just the same?
>
Extended stored procedures are so dangerous to the stability of the database
server that they should be used very, very carefully.
In SQL 2005 CLR integration provides a safe way to extent the SQL engine
with custom calculations.
David