Showing posts with label functions. Show all posts
Showing posts with label functions. Show all posts

Thursday, March 22, 2012

Calling native code from a trigger.

I've been searching for a bit but I can't seem to find a difinitive answer.

Can an SQL Server trigger call native C/C++ functions? If so, what is the mechanism?

Thanks in advance.

My knee-jerk reaction is that this sounds like a very bad idea, but perhaps not. What are you trying to accomplish?|||Moving thread to the more appropriate forum.|||

You could do that by creating a CLR procedure or function that wrapped the Win32 API calls.

What are you attemping to accomplish?

|||I was thinking of having a trigger that would call a native function that could do some needed tasks outside the SQL server. Things like post a message to an open mail slot on either the same or a different server so that another service can perform some work. After talking with on of the other developers, we will probably send the messages from his app. that is connected to the SQL server. I was thinking of having a trigger do it because it would remove him from having to manage the messages. Also a thought for future development.|||

Personally, I wouldn't have a TRIGGER engage any outside service. It provides too many additional surfaces for disruption -the TRIGGER hangs waiting for the outside service ...

A better approach is to have the TRIGGER insert the relevant data into a queueing table.

Then have a separate SQL Agent Job that constantly runs checking the queue, and upon finding a row of data, processes that row in whatever fashion is appropriate (sending mail, logging, etc.)

|||

In my case, it would just post a message into a queue and a thread would be watching the queue. The processing would happen on another process or service running multi threaded code. The trigger would probably return in a few ms. This would probably be faster than a lot of ODBC calls and the other service can simply wait on an event using no CPU cycles until an event is signalled.

Different ways to skin the cat I guess. Coders like to have code do the work and DBA's like the DBMS to do the work. Also a factor of what you are comfortable with.

Calling native code from a trigger.

I've been searching for a bit but I can't seem to find a difinitive answer.

Can an SQL Server trigger call native C/C++ functions? If so, what is the mechanism?

Thanks in advance.

My knee-jerk reaction is that this sounds like a very bad idea, but perhaps not. What are you trying to accomplish?|||Moving thread to the more appropriate forum.|||

You could do that by creating a CLR procedure or function that wrapped the Win32 API calls.

What are you attemping to accomplish?

|||I was thinking of having a trigger that would call a native function that could do some needed tasks outside the SQL server. Things like post a message to an open mail slot on either the same or a different server so that another service can perform some work. After talking with on of the other developers, we will probably send the messages from his app. that is connected to the SQL server. I was thinking of having a trigger do it because it would remove him from having to manage the messages. Also a thought for future development.|||

Personally, I wouldn't have a TRIGGER engage any outside service. It provides too many additional surfaces for disruption -the TRIGGER hangs waiting for the outside service ...

A better approach is to have the TRIGGER insert the relevant data into a queueing table.

Then have a separate SQL Agent Job that constantly runs checking the queue, and upon finding a row of data, processes that row in whatever fashion is appropriate (sending mail, logging, etc.)

|||

In my case, it would just post a message into a queue and a thread would be watching the queue. The processing would happen on another process or service running multi threaded code. The trigger would probably return in a few ms. This would probably be faster than a lot of ODBC calls and the other service can simply wait on an event using no CPU cycles until an event is signalled.

Different ways to skin the cat I guess. Coders like to have code do the work and DBA's like the DBMS to do the work. Also a factor of what you are comfortable with.

sql

Calling methods, functions threw Extended SP in a DLL

Hi,

I alredy tried to search this problem in last posts, but I couldn't
find the answer.
I try to access via Extended SP the method in a dll.

I registered the dll as a ExSP, with a name of method. But after
calling it in T-SQL, I became such a error message:

[Microsoft][ODBC SQL Server Driver][SQL Server]Cannot find the
function SendGeneralNotify_FromA in the library [LibraryName.dll].
Reason: 127(error not found).

In this dll I have only one class an it has events, properities and
methods.
I will to call one of these methods.

aha ... very importand. Please don't say that this dll should be
written in c++ because it is made like that (no VB).

Maybe somebody of you have an example how I should call it, to became
an access on this dll?

Sorry for my not well english.

With best regards, looking forward for reply

----------
Matik
marzec@.sauron.xo.plMatik,

> In this dll I have only one class an it has events, properities and
> methods.
> I will to call one of these methods.
> aha ... very importand. Please don't say that this dll should be
> written in c++ because it is made like that (no VB).

If I understand you correctly, you've written a DLL in VB 6 (or 5) and you
want to call it as an extended stored procedure. Unfortunately, VB 6 can't
export a function, which is what an extended stored procedure must do. You
have three choices:

1. Use a different language (C, C++, Delphi, etc): I understand that you
don't want to do this. I don't know if VB.NET will let you export a
function, but if it will that might be an option.

2. Buy a tool from Desaware that enables you to export a function from VB 6.
I don't remember the name and I've never used it, but you should be able to
find it at Desaware.

3. Instead of using the extended stored procedure functionality, use the
sp_OA... stored procedures to instantiate your class and call the method
you want. Check books online or google for examples: sp_OACreate is a good
one to start with an google.

My standard extended sp warning: extended stored procedure are dangerous. I
refuse to allow them where I work because a single errant pointer can cause
untold damage. I know people use them to great effect, but it gives me the
shivers. I feel the same way (but not as strongly) about the sp_OA...
procedures. My real advice is to find another way to do it. And... if
writing an extended sp doesn't make you nervous, you probably shouldn't
write one :)

Craig|||Hej Craig,

> If I understand you correctly, you've written a DLL in VB 6 (or 5) and you
> want to call it as an extended stored procedure. Unfortunately, VB 6 can't
> export a function, which is what an extended stored procedure must do. You
> have three choices:

Maybe I explained it a little nfortunately. One more time:
- this is a object (in dll) which has properities and methodes.
- I must call one of these methods,
- it is written in C++,

If I try to do that via ExSP, it do not works (I have this error as
above alredy written).
If I do that with sp_OA, then It works ... but not like I expected:-)

First, I create the object:

exec @.iRetVal = sp_OACreate '{034188F2-8DBC-4613-829A-76D5279C35A3}',
@.iObject OUTPUT,1
EXEC sp_OAGetErrorInfo @.iObject, @.sSource OUT, @.sDescription OUTPUT
IF @.iRetVal <> 0
begin
set @.sLog = 'No object created. Source: ' + @.sSource + '
Description: ' + @.sDescription
print @.sLog
end

This is without problems.
Then I try to call this methode:

exec @.iRetVal = sp_OAMethod @.iObject,'SendNotification_FromA',
@.sProperty OUT, @.nMessageNr = 555, @.bstrDateTime = @.dDateEVT,
@.textFromA1 = @.sText1 OUTPUT, @.textFromA2 = @.sText2 OUT
EXEC sp_OAGetErrorInfo @.iObject, @.sSource OUT, @.sDescription OUT

IF @.iRetVal <> 0
begin
set @.sLog = 'Source: ' + @.sSource + ' Description: ' +
@.sDescription
print @.sLog
end

IF @.iRetVal <> 0
begin
set @.sLog = 'Source: ' + @.sSource + ' Description: ' +
@.sDescription
print @.sLog
end

print @.iRetVal

PRINT @.sProperty
PRINT @.sText1
PRINT @.sText2

... and I became no errors, but the values are the same I set at the
beginning.
On my pc works also the small software, which should capture this
values.
This software recieves the data sended with this method.
I wrote the small VB programm, where I call the same method, with the
same values, and then the second programm reives the data ...

Hopeless?

Thank You for Your cindly reply.

Matik|||Matik,

Please see inline

> Maybe I explained it a little nfortunately. One more time:
> - this is a object (in dll) which has properities and methodes.
> - I must call one of these methods,
> - it is written in C++,

Ah... I see. I apologize for the misunderstanding.

> If I try to do that via ExSP, it do not works (I have this error as
> above alredy written).
> If I do that with sp_OA, then It works ... but not like I expected:-)

If you already have C++ and you really want an ExSP then you can look in SQL
Server Books Online for the topic "Extended Stored Procedure Programming"
under the main heading "Build SQL Server Applications". Basically you would
need to #include a special header or two and export a very specific function
type. But since you already have a COM object...

> First, I create the object:

Remember that the object identifier you're getting is basically a handle to
a COM interface pointer, so you need to treat it like you would any other
resource: if sp_OACreate succeeds, then you need to call sp_OADestroy.

Another gotcha that seems simple but people seem to forget: the COM object
needs to be registered on the SQL Server (if you're instantiating a local
COM Server, which you are here). I watched people nearly strangle a
laughing coworker when they realized that registering a COM component on the
computer running Query Analyzer isn't the same :) I know this isn't your
problem, but if it hasn't bitten you yet, it will...

<whitespace edited>
> exec @.iRetVal = sp_OAMethod
> @.iObject,
> 'SendNotification_FromA',
> @.sProperty OUT,
> @.nMessageNr = 555,
> @.bstrDateTime = @.dDateEVT,
> @.textFromA1 = @.sText1 OUTPUT,
> @.textFromA2 = @.sText2 OUTPUT

OK, I couldn't see what was wrong, so I created a quick COM object (I
cheated and used VB :) that matched what I *think* your COM object looks
like. Here's the IDL:

HRESULT SendNotification_FromA(
[in] long nMessageNr,
[in] BSTR bstrDateTime,
[in, out] BSTR* textFromA1,
[in, out] BSTR* textFromA2,
[out, retval] BSTR* );

This is the important part: you need to make sure that the parameter names
match up in the call to sp_OAMethod and your IDL. Since you're trying to
get output parameters, you also need to make sure that textFromA1 and
textFromA2 are [in,out] and are a datatype that allows that (such as BSTR*).

Also, you need to make sure that you've correctly implemented IDispatch and
that all your parameters are OLE compatible. A good test is to re-write
your VB program to use late-binding. For example (untested and coded in my
newsreader):

Dim obj As Object
Dim s, a1, a2
Set obj = CreateObject("SomeLib.SomeClass")

a1 = "in 1"
a2 = "in 2"
s = obj.SendNotification_FromA(555, "SomeDateTime", a1, a2)

MsgBox s & vbcrlf & a1 & vbcrlf & a2

Set obj = Nothing

Regardless, I got it to work, so I imagine there's something wrong with the
way your COM code is working. After checking your IDL and matching T-SQL
code, I would try stripping the COM method down to as little as possible
(maybe just log out input parms and set the output parms to constants) and
see if you can get that to work.

Good Luck,

Craig

Calling Functions on another database

Hey guys, I recently found out u can actaully JOIN tables that are on different dbs as long as they are on the same SQL Server by specifying [DATABASE].[DATABASEOWNER].[TABLE]. I now have a question tho. Can you access functions the same way? i have tried using the same syntax, but I get an error saying 'Invalid object name'

Any help would be great.

Thanks!You can as long as permissions are set correctly. I do it all the time. You must be missing something, because it is possible. Is the function what is showing as invalid or is there something inside the function that it thnks is invalid?

And actually, you can join tables and use objects from other servers if you have linked servers set up.|||ah thanks, you're right, i had changed the object owner using sp_changeobjectowner and forgot that the permissions get dropped. Thanks alot!sql

Calling functions in an expression

I have a function in the Report Code of one of my reports and an expression
that references it. Here is the expression that is in the details row:
=Iif(Code.Check(Fields!fullname.Value), 0,
Code.AddClient(Fields!fullname.Value))
The Check function basically looks in an array to see if the name is in the
array already. If it is, the expression should return 0. If it is not in the
array, it should call AddClient() to add the client and increment the
variable Total (Which is also declared in the Report Code). However, whenever
this expression runs, Total gets incrememnted no matter what. Even if the IIf
condition is false.
Is there something wrong with the way I am doing this?It is ok, is there any error in that case what exactly is the error?
Amarnath
"Matt M" wrote:
> I have a function in the Report Code of one of my reports and an expression
> that references it. Here is the expression that is in the details row:
> =Iif(Code.Check(Fields!fullname.Value), 0,
> Code.AddClient(Fields!fullname.Value))
> The Check function basically looks in an array to see if the name is in the
> array already. If it is, the expression should return 0. If it is not in the
> array, it should call AddClient() to add the client and increment the
> variable Total (Which is also declared in the Report Code). However, whenever
> this expression runs, Total gets incrememnted no matter what. Even if the IIf
> condition is false.
> Is there something wrong with the way I am doing this?|||There is no error, but rather this is what is being displayed in the report:
0 Case1
1 Case2
2 Case3
3 Case4
4 Case5
The first column displays the Total variable that gets incremented by the
AddClient() function. It should only be incremented if the Check() returns
true in any of the Cases. But instead, it gets incremented every row.
"Amarnath" wrote:
> It is ok, is there any error in that case what exactly is the error?
> Amarnath
> "Matt M" wrote:
> > I have a function in the Report Code of one of my reports and an expression
> > that references it. Here is the expression that is in the details row:
> >
> > =Iif(Code.Check(Fields!fullname.Value), 0,
> > Code.AddClient(Fields!fullname.Value))
> >
> > The Check function basically looks in an array to see if the name is in the
> > array already. If it is, the expression should return 0. If it is not in the
> > array, it should call AddClient() to add the client and increment the
> > variable Total (Which is also declared in the Report Code). However, whenever
> > this expression runs, Total gets incrememnted no matter what. Even if the IIf
> > condition is false.
> >
> > Is there something wrong with the way I am doing this?|||You still need to evaluate the expression... (i.e. you need an = sign)
change it to:
=Iif(Code.Check(Fields!fullname.Value) = 1, 0,
Code.AddClient(Fields!fullname.Value))
and I am assuming that you are returning a zero for false and 1 for true...
=-Chris
"Matt M" <MattM@.discussions.microsoft.com> wrote in message
news:2FE6A608-EE89-407D-AAED-A17385D6952F@.microsoft.com...
>I have a function in the Report Code of one of my reports and an expression
> that references it. Here is the expression that is in the details row:
> =Iif(Code.Check(Fields!fullname.Value), 0,
> Code.AddClient(Fields!fullname.Value))
> The Check function basically looks in an array to see if the name is in
> the
> array already. If it is, the expression should return 0. If it is not in
> the
> array, it should call AddClient() to add the client and increment the
> variable Total (Which is also declared in the Report Code). However,
> whenever
> this expression runs, Total gets incrememnted no matter what. Even if the
> IIf
> condition is false.
> Is there something wrong with the way I am doing this?|||I'm actually returning a boolean true or false with it. I tried returning a 0
or a 1 and still does the same thing.
"Chris Conner" wrote:
> You still need to evaluate the expression... (i.e. you need an = sign)
> change it to:
> =Iif(Code.Check(Fields!fullname.Value) = 1, 0,
> Code.AddClient(Fields!fullname.Value))
> and I am assuming that you are returning a zero for false and 1 for true...
> =-Chris
> "Matt M" <MattM@.discussions.microsoft.com> wrote in message
> news:2FE6A608-EE89-407D-AAED-A17385D6952F@.microsoft.com...
> >I have a function in the Report Code of one of my reports and an expression
> > that references it. Here is the expression that is in the details row:
> >
> > =Iif(Code.Check(Fields!fullname.Value), 0,
> > Code.AddClient(Fields!fullname.Value))
> >
> > The Check function basically looks in an array to see if the name is in
> > the
> > array already. If it is, the expression should return 0. If it is not in
> > the
> > array, it should call AddClient() to add the client and increment the
> > variable Total (Which is also declared in the Report Code). However,
> > whenever
> > this expression runs, Total gets incrememnted no matter what. Even if the
> > IIf
> > condition is false.
> >
> > Is there something wrong with the way I am doing this?
>
>|||It means it is always returning true... Try hard code just for testing
purpose. hard code it to false and see whether it increments.
Amarnath
"Matt M" wrote:
> There is no error, but rather this is what is being displayed in the report:
> 0 Case1
> 1 Case2
> 2 Case3
> 3 Case4
> 4 Case5
> The first column displays the Total variable that gets incremented by the
> AddClient() function. It should only be incremented if the Check() returns
> true in any of the Cases. But instead, it gets incremented every row.
>
> "Amarnath" wrote:
> > It is ok, is there any error in that case what exactly is the error?
> >
> > Amarnath
> >
> > "Matt M" wrote:
> >
> > > I have a function in the Report Code of one of my reports and an expression
> > > that references it. Here is the expression that is in the details row:
> > >
> > > =Iif(Code.Check(Fields!fullname.Value), 0,
> > > Code.AddClient(Fields!fullname.Value))
> > >
> > > The Check function basically looks in an array to see if the name is in the
> > > array already. If it is, the expression should return 0. If it is not in the
> > > array, it should call AddClient() to add the client and increment the
> > > variable Total (Which is also declared in the Report Code). However, whenever
> > > this expression runs, Total gets incrememnted no matter what. Even if the IIf
> > > condition is false.
> > >
> > > Is there something wrong with the way I am doing this?

Calling Functions

Dear Everybody,

Hi again!

Supposing I have an SQL Server Function named Fxn1 which returns a VARCHAR(6) value. I want to use this returned value in another function named Fxn2 but Fxn2 accepts a parameter of type INT. Fxn2 itself returns an INT value. This has to be achieved in a single line.

The following line of code will not work in SQL Server. How should I achieve this?

declare @.Res INT
EXEC @.Res = Fxn2 (CONVERT( INT, Fxn1 ))

Thanx in advance!Just curioius, but have you tried talking to the TA or your instructor? Its really important that you talk to them when you are stumped on homework, they need the feedback as much as you need the help finding the solution.

-PatP|||No thx for the suggestion. :rolleyes:

I always thought that this forum had people who cud come up with suggestions which were technical in nature!|||It does, but we still won't do your homework!

-PatP|||First of all stop calling this homework. You cannot pass judgements like that. To me it was a genuine problem that's why I referred it to this forum. Might be not for u.

If u r not interested, gr8. But keep ur thoughts to urself.|||"This has to be achieved in a single line."?

Are you running out of lines on your computer?

You may just need to create a single function that combines the logic of the two you have.|||I don't have any problem giving legitimate help (read a few thousand of my posts if you'd like to confirm that), but based on the attitude that you've displayed and the grammer and spelling that you've used (or more accurately failed to use), you appear to me to be a rather rude kid that is sqawking because they got caught trying to get someone to do their homework. If I've misinterpreted something, I'm sorry, but that is how you appear to me at the moment.

Based on the way you presented the question in your original posting, it reads like homework. Are you saying that it isn't homework? If not, can you give us a little background in what you are trying to do, and more importantly why it needs to be accomplished in a single line?

-PatP|||Are you running out of lines on your computer?I just hate it when that happens, don't you?

-PatP|||What error are you getting when you execute the statement? Obviously
EXEC @.Res = Fxn2 (CONVERT( INT, Fxn1 ))
...will error out if Fxn1 returns a string that cannot be converted to an INT.
Also, post the actual statement you are sending.|||Dear blindman (although I hate to use that term to address u),

First of all thx for ur concern & help. Can I show the audacity to ask your real name?

Second of all, lets move to my actual problem..

I have several procedures and functions in Oracle which I have to convert to SQL Server syntax. The Fxn1 and Fxn2 names that I had used was just to present the problem to the forum in a simple manner.
In one of the functions named CREATE_TRIPS_SCHED, a SELECT statement has been included (the result of which has been used in another query) which is as follows :

SELECT 'P'||T.T_ID, T.S_TIME, T.END_TIME,
NVL(T.DESIRED_TIME, MIN_TO_AMPM( TO_MINUTES(TO_NUMBER(AMPM2FULLHRS(T.EST_TIME))))),
T.DISP, DECODE(T.WHEEL_CHAIR,'Y',5,2)
FROM DISPATCH_TRIPS T
WHERE T.R_NUM LIKE 'X%'

In the above statement, MIN_TO_AMPM, TO_MINUTES and AMPM2FULLHRS are all UDFs, out of which MIN_TO_AMPM and TO_MINUTES fxns return INTEGER values and AMPM2FULLHRS returns a VARCHAR value.

The conversion for SQL Server that I had done is as under :

SELECT 'P' + T.T_ID, T.S_TIME, T.END_TIME,
(CASE T.DESIRED_TIME WHEN ISNULL THEN MIN_TO_AMPM( TO_MINUTES(CONVERT (INT, AMPM2FULLHRS (T.EST_TIME)))) ELSE T.DESIRED_TIME END),
T.DISP, (CASE T.WHEEL_CHAIR WHEN 'Y' THEN 5 ELSE 2 END)
FROM DISPATCH_TRIPS T
WHERE T.R_NUM LIKE 'X%'

And the error msg that I am getting is this :

Server: Msg 195, Level 15, State 10, Procedure CREATE_TRIPS_SCHED, Line 25
'AMPM2FULLHRS' is not a recognized function name.
Server: Msg 156, Level 15, State 1, Procedure CREATE_TRIPS_SCHED, Line 56
Incorrect syntax near the keyword 'END'.
Server: Msg 156, Level 15, State 1, Procedure CREATE_TRIPS_SCHED, Line 68
Incorrect syntax near the keyword 'END'.

I have to do this conversion without introducing other fxns of mine. So, this is the actual problem. I hope I have been able to get across my problem!

Thx again! :)|||Pat,

At least you had the decency to be 'sorry' even if my turning 'rude' prompted you to do so.

Originally Posted by Pat Phelan
It does, but we still won't do your homework!
Having a few thousand posts does not give you the right to be judgemental. It also does not entitle you to speak on behalf of the whole forum.

P.S. Are u always like that?|||Perhaps adding the owner of the function when calling the function helps (db.owner.function)?|||It appears that my first impression may have been wrong. Based on your last post to blindman, you do seem to have a good grasp of SQL and a practical reason for making your original request.

I think you should have success if you use:SELECT @.Res = dbo.Fxn2 (CONVERT( INT, dbo.Fxn1() ))This ought to safely degenerate into:SELECT @.Res = dbo.Fxn2 (dbo.Fxn1() )In answer to your other question, yes, especially when this forum is barraged with kids looking for someone to do their homework for them, I tend to react with considerable skepticism to posts that are presented that way. My intent is to "red flag" those posts for other forum members, so that they will consider whether they want to spend their time working on a problem that is likely going to be turned in by a kid with no appreciation and no clue. The other forum members can use their own judgement, I'm just trying to make sure that they think before they "burn daylight" answering a post that I perceive as looking for an opportunity to plagerize.

I've repeatedly had my work turned in by students, whose teachers have recognized my style and contacted me. That probably makes me overly sensitive to the issue. I also think that there is a real ethical problem there too, and being in a position where ethical behavior is probably more important than technical expertise, that is very important to me.

Based on the begining of this thread, I had no reason to suspect that you were anything other than an apprentice juvenile delinquent, trolling to find someone that would do their assignment for them. Based on your post to Blindman, it appears that my first impression was wrong, so I responded differently in this post. As I've said before, I have no problem giving legitmate technical assistance, but I outright refuse to allow someone to take advantage of me (or anyone else without their approval).

-PatP|||Knighthassan,

Pat, myself, and others have given literally thousands of bits of advice and help to people who have posted on these boards, all of it free. If Pat made a mistake about your situation then so be it, but he had reasons to be suspicious. People asking for free advice should be less disrespectful, especially of people like Pat who is arguably the most knowledgable SQL Server expert on this forum. The fact that he took considerable time to review your complex code and propose a solution after last few posts you made shows how gracious he is. I hope his solution was helpful.|||blindman and Pat,

Thx to u both my problem is resolved. I also realize that my language has been a bit too harsh at times but something there got to me. Anyways, no hard feelings and thx again.|||blindman and Pat,

Thx to u both my problem is resolved. I also realize that my language has been a bit too harsh at times but something there got to me. Anyways, no hard feelings and thx again.No problem, and I'm glad that your problem has been fixed.

I rarely miss on issues like this, but of course when I do then it's a doozie. Out of several hundred "homework" calls that I've made, this is only the second one that I know where my initial call was wrong.

Right now I'm probably overly sensitive to it, since American schools are just coming back from the Thanksgiving holiday which meant that quite literally tens of thousands of assignments were due last week.

I noticed that you'd dived into some other message threads and contributed to them too. I hope that you decide to stick around and join in the fun! Lord knows that there is no shortage of questions, and it always helps to have a different perspective (although mine is usually quite "different" all by itself!).

-PatP|||I'm glad we (mosty Pat) were able to assist you, and yeah working with databases can be frustrating in itself sometimes, but we try to keep things light on this forum so no hard feelings and post again with both questions and advice.|||Pat, myself, and others have given literally thousands of bits of advice and help to people who have posted on these boards, all of it free.

Thank you

If Pat made a mistake about your situation then so be it, but he had reasons to be suspicious.

Umm, maybe not

People asking for free advice should be less disrespectful

Absolutely...why do people get so worked up? Who cares what soemone says? This always cracks me up.

especially of people like Pat who is arguably the most knowledgable SQL Server expert on this forum.

Well, could be, but I know Nigel posts here from time to time.

The fact that he took considerable time to review your complex code and propose a solution after last few posts you made shows how gracious he is. I hope his solution was helpful.

I think he'd still be having trouble. Post the actuall CREATE FUNCTION statements for both functions...personally they look more like a sproc to me...

And as for B. Lindman, you could probaly say "Yo, Blind dude!"

I always wondered where he got a braille keyboard..|||And as for B. Lindman, you could probaly say "Yo, Blind dude!"

I always wondered where he got a braille keyboard..Ah, Braille keyboards are no biggie to get. The difference is only in a few keys, but the tactile feedback for the indicators is the challenging part.

-PatP|||Wut's tuff iss finding a ceeing I dogg thata caan tipe woof a dam.

Bad dog! Bad!|||Originally Posted by Brett Kaiser
I always wondered where he got a braille keyboard..

A braille display and a braille mouse too! The world gets curiouser and unfathomable each passing day..

:D|||A braille display and a braille mouse too! The world gets curiouser and unfathomable each passing day..You say that as though it were a bad thing! ;)

As a side note, couldn't you get into some kind of trouble for feeling the bumps on a Braille mouse in the office ?

-PatP|||Depends on what you mean by mouse...

Calling external functions from SQL SELECT

Does anyone know whether (and if so how :) it is possible to call external
functions from SQL's SELECT statement in a similar way that MS Access allows
you call code in its VBA modules?
For example, I'd like to be able to do this:
SELECT Name, DOB, VeryComplexFunction([Table.Numeric]) AS NumericResult
FROM Table
where,
VeryComplexFunction is a function that I (or some other 3rd party)
provide, perhaps in a DLL, but which cannot be implemented in a UDF
Now, I currently do that in Access, but now need to migrate to SQL.
I be very grateful for for any help or pointers that anyone can offer.
Thanks in adavnce.A Shasore,
Take a look at sp_OA... stored procedures in BOL.
Ilya
"A Shasore" <AShasore@.discussions.microsoft.com> wrote in message
news:FF3F6C55-AB9A-4228-95C6-B0E564031EE9@.microsoft.com...
> Does anyone know whether (and if so how :) it is possible to call external
> functions from SQL's SELECT statement in a similar way that MS Access
allows
> you call code in its VBA modules?
> For example, I'd like to be able to do this:
> SELECT Name, DOB, VeryComplexFunction([Table.Numeric]) AS NumericResult
> FROM Table
> where,
> VeryComplexFunction is a function that I (or some other 3rd
party)
> provide, perhaps in a DLL, but which cannot be implemented in a UDF
> Now, I currently do that in Access, but now need to migrate to SQL.
> I be very grateful for for any help or pointers that anyone can offer.
> Thanks in adavnce.
>|||Hello Ilya,
Thanks for that, I'll take another look. Although from what (little) I know
of OLE Object support, I don't it can achieve the same thing.
In the meantime, thanks for your reply...
A.
"Ilya Margolin" wrote:

> A Shasore,
> Take a look at sp_OA... stored procedures in BOL.
> Ilya
> "A Shasore" <AShasore@.discussions.microsoft.com> wrote in message
> news:FF3F6C55-AB9A-4228-95C6-B0E564031EE9@.microsoft.com...
> allows
> party)
>
>

Tuesday, March 20, 2012

Calling extended stored procs from a function

I know you cannot call functions from a stored proc.. only extended stored
procs otherwise you get this message
"Server: Msg 557, Level 16, State 2, Procedure nextval2, Line 9
Only functions and extended stored procedures can be executed from within a
function."
So, to get around it, I am using sp_Executesql which IS an extended stored
proc but I am still getting the error. PLease explain?
Thanks!!!!!
ALTER function nextval2
( @.sequence varchar(100)) returns int
AS
BEGIN
declare @.sequence_id int
set @.sequence_id = -1
exec sp_executesql N'update sequences set sequence_id = sequence_id + 1'
select @.sequence_id = max(sequence_id)
from sequences
RETURN @.sequence_id
ENDThere are 2 ways that I know of to maintain variable information between
calls to a function,
1) Use OPENQUERY to pass through an UPDATE or INSERT to a loopback linked
server.
2) Use sp_OA calls to access parameters on a previously declared object (e.g
VBScript.RegExp)
I suspect these are just about as dangerous as each other :)
Mr Tea
"Amelia" <Amelia@.discussions.microsoft.com> wrote in message
news:C92D80A6-1367-4BF5-9BE2-65BD8C54EC12@.microsoft.com...
>I know you cannot call functions from a stored proc.. only extended stored
> procs otherwise you get this message
> "Server: Msg 557, Level 16, State 2, Procedure nextval2, Line 9
> Only functions and extended stored procedures can be executed from within
> a
> function."
> So, to get around it, I am using sp_Executesql which IS an extended stored
> proc but I am still getting the error. PLease explain?
> Thanks!!!!!
> ALTER function nextval2
> ( @.sequence varchar(100)) returns int
> AS
> BEGIN
> declare @.sequence_id int
> set @.sequence_id = -1
> exec sp_executesql N'update sequences set sequence_id = sequence_id + 1'
> select @.sequence_id = max(sequence_id)
> from sequences
> RETURN @.sequence_id
> END
>|||Thanks LEe.
"Lee Tudor" wrote:

> There are 2 ways that I know of to maintain variable information between
> calls to a function,
> 1) Use OPENQUERY to pass through an UPDATE or INSERT to a loopback linked
> server.
> 2) Use sp_OA calls to access parameters on a previously declared object (e
.g
> VBScript.RegExp)
> I suspect these are just about as dangerous as each other :)
> Mr Tea
> "Amelia" <Amelia@.discussions.microsoft.com> wrote in message
> news:C92D80A6-1367-4BF5-9BE2-65BD8C54EC12@.microsoft.com...
>
>

Calling CLR functions from MDX query

Hi,

I am finding it extremely tricky in getting the CLR function in C# to return anything useful that doenst contain an error message. My function in the assembly SqlServerProject1 and the class UserDefinedFunctions is fnBitwise and performs a bitwise operation on the two input params.

select SqlServerProject1.UserDefinedFunctions.fnBitwise(24,8) on 0,

[measures].[Discount Amount] on 1

from [analysis services tutorial]

OR

Call SqlServerProject1.UserDefinedFunctions.fnBitwise(24,8)

Are not producing results, instead I get error msgs.

I have been getting msgs such as

Execution of the managed stored procedure fnBitwise failed with the following error: Microsoft::AnalysisServices::AdomdServer::AdomdException.

OR

Parser: The end of the input was reached.

Please could someone help as it seems like there is not clear help on this. What Im trying to do is to perform a bitwise operation and summing the results to create a new calculated member. Unfuortunately, Analysis services doesn't allow for bitwise operations, so I had created a CLR function in VS.Net to perform the operation. Now, while this works fine in SQL Server after being deployed there by VS.Net SQLServerProject, I am more inportantly trying to get this to work in AS using an MDX query to test the function. The SQL Server project doesn't let me add a reference to the class library that I may need as described by http://solidqualitylearning.com/blogs/dejan/archive/2005/12/01/1492.aspx .

The CLR Function is very simpe and is shown below:

using System;

using System.Data;

using System.Data.SqlClient;

using System.Data.SqlTypes;

using System.Data.OleDb;

using Microsoft.SqlServer.Server;

public partial class UserDefinedFunctions{

[Microsoft.SqlServer.Server.SqlFunction]

public static SqlInt32 fnBitwise(byte varA, byte varB)

{

long result = varA & varB;

SqlInt32 b;

if (result != 0)

{

b = 1;

}

else

{

b = 0;

}

return b;

}

};

I need a way of getting the result or the bitwise operation out in the MDX query so I can then create my calculated member in SQL Server Business Intelligence Development Studio Cube Designer.

Thanking you in advance.

Rob

There are two problems here. First of all AS doesn't seem to like SQL Server data types; I replaced SqlInt32 with int and got the sproc working ok:

using System;

using System.Data;

using System.Data.SqlClient;

using System.Data.SqlTypes;

using System.Data.OleDb;

using Microsoft.SqlServer.Server;

public partial class UserDefinedFunctions

{

[Microsoft.SqlServer.Server.SqlFunction]

public static int fnBitwise(byte varA, byte varB)

{

long result = varA & varB;

int b;

if (result != 0)

{

b = 1;

}

else

{

b = 0;

}

return b;

}

};

Secondly, neither of the examples of calling the sproc you give in your post are going to work because it returns an integer value and you're calling it places where AS is expecting either a member or a set (in the first example) or a cellset. You need to call the sproc within a calculated member definition, for example:

with member measures.test as ASStoredProc.fnBitWise(8,24)

select measures.test on 0 from mycube

HTH,

Chris

|||

Thanks Chris.

That's great.

Regards

Rob

Sunday, March 11, 2012

Calling a Function from a Stored Procedure

Hello all,

I'm trying to construct a select statement in a stored procedure that filters based on the returned values of a number of functions. My function works fine, but when I try to call the function from the stored procedure I get an error.

I'm going to try explain the thought process behind what I'm doing. Hope I make enough sense.
The purpose of the stored procedure is to perform a wildcard search on a tool. The tool contains a number of FK that link to different tables (e.g., manufacturer, vendor). So I'm creating functions that also search the manufacturer and vendor and return the matching IDs.

Example of tool SELECT statement:

SELECT tool_number, tool_descriptionFROM toolWHERE tool_manufacturerIN (UDFmanufacturer_SearchName(@.search_string)

This gives me an error:
'UDFmanufacturer_SearchName' is not a recognized built-in function name.

Function code (removed some wrapping code for simplicity):

SELECT manufacturer_idFROM manufacturerWHERE manufacturer_nameLIKE'%' + @.search_string +'%'
These statements both work if I run a independent query: 
SELECT *FROM UDFmanufacturer_SearchName('mol')

SELECT *FROM toolWHERE tool_manufacturerIN (SELECT *FROM UDFmanufacturer_SearchName('mol'))

This code fails:

SELECT *FROM ato_toolWHERE ato_tool_manufacturerIN (UDFmanufacturer_SearchName('mol')) 
I'm stuck. I haven't been able to find anything that shows me where I'm going wrong. Any thoughts or suggestions are appreciated.

Thanks,
Jay


You have to use a SELECT FROM function and not directly in the IN clause. Also use the prefix "dbo." for the function and see if it helps.

SELECT *FROM toolWHERE tool_manufacturerIN (SELECT *FROMdbo.UDFmanufacturer_SearchName('mol'))
|||

That was it. I thought I could use the function without needing the " SELECT * " in front.

Thanks for your help.

|||

The above post is absolutely correct.

UDFmanufacturer_SearchName is a table valued function (fancy for it returns a table/resultset). If you then think of UDFmanufacturer_SearchName('mol') as being a table, then

SELECT *
FROM ato_tool
WHERE ato_tool_manufacturerIN (UDFmanufacturer_SearchName('mol'))

isn't valid for the same reasons that:

SELECT *
FROM ato_tool
WHERE ato_tool_manufacturerIN (tool_manufacturer)

isn't valid.

So because tables aren't valid where you've placed it, it's looking for a different type of function, like one that returns a string, date, or number. It can't find one, so it says it can't find the function. Also, you should always prefix your function names with 'dbo.' or the correct schema. It may work without it in some places, but I believe syntactically it's wrong (sloppy). Don't be suprised if a service pack, hotfix, or the next version of SQL Server starts to fail on it.|||

Thanks for the explanation, it was helpful.

Hadn't thought about the schema prefix. Will keep it in mind.

Thanks.

Thursday, March 8, 2012

Calling a .NET assembly

I have implemented a c#-dll and added it to the assembly cache.
My question is if there exists some other way of calling functions in it other than using a script task?

Using a script task works well, but I think it would be nicer if there was some sort of dll-task analoguos to the web service task.

Thanks for some comments!

No, there is no "Assembly Task". Not sure what such as task would give you really as there are so many variations.

I had considered one as a development, but I only see this as being worth the effort for a Transform, supporting limited single call methods.|||Ok, thanks Darren.

But "so many variations" ?
Don't know if I get what you mean, but aren't there just as many variations for a web service task?
|||Have you tried the WS task? It is not very flexible, no dynamic parameter support for example. That is what I mean. The WS task also has the advantage of avoiding constructors, and all methods are of course accessible through XMl therefore type conversions are already handled from string, if you went for native soap calls. This reduces the complexity of type conversion issues. Soap has addressed all the messy issues already, as well as imposing some limitations in itself.

Would you expect it to be limited to static methods? If not how would you define constructor parameters? How would you handle all the data types for methods dynamically? How would you access a dynamic list of input parameters when the task must define fixed properties up front? You cannot access a collection through expressions. What about ref and out parameters?

The signature of a method has a wide variety of options, and coping with all of these would be a lot of work.

It is all possible, albeit with some predefined constraints, but the value I see is limited when you can do all this and more with the script task. Not a viable component commercially in my opinion, and I only have so much time for freebies. Feel free to disagree though.|||Ok, thank you Darren... I can see more clearly now! =)
Yeah, I agree with you after reading your explanations. So thanks again!
|||We actually considered a ".Net Assembly" task. But, really, that's what the script task is.

callin functions inside queries

im trying to make this function in tsql

create function isolatedLeptons
(@.idevent INT)
Returns TABLE
AS
Return select l.*
from lepton as l, event as e
where e.id = l.eventid and pt(l.id) > 7.0 and abs(eta(l.id))<2.4
END

GO

select * from lepton;

but it trow me this error

Msg 195, Level 15, State 10, Procedure isolatedLeptons, Line 9
'pt' is not a recognized built-in function name.

pt is defined as

create function pt
(@.idpt INT)
Returns Real
AS
BEGIN
Return ( select sqrt(a.px*a.px + a.py*a.py)
from abstractparticle as a
where @.idpt = a.id)
END

GO

Hi,

you need to use dbo.pt(l.id).

--
Regards,
Daniel Kuppitz

|||

Please do not use scalar UDFs for simple tasks like this. It is overkill in terms of performance and probably manageability too. Use the query expression inline like:

create function isolatedLeptons
(@.idevent INT)
Returns TABLE
AS
Return select l.*
from lepton as l, event as e
where e.id = l.eventid

and (select sqrt(a.px*a.px + a.py*a.py)
from abstractparticle as a
where a.id = l.id) > 7.0

and abs(eta(l.id))<2.4

Or if you want to go the UDF route use an inline TVF instead like:

create function pt
(@.idpt INT)
returns table
AS
return ( select sqrt(a.px*a.px + a.py*a.py) as val
from abstractparticle as a
where @.idpt = a.id)
GO

create function isolatedLeptons
(@.idevent INT)
Returns TABLE
AS
Return select l.*
from lepton as l, event as e
where e.id = l.eventid

and (select a.val

from pt(l.id)) > 7.0

and abs(eta(l.id))<2.4

Wednesday, March 7, 2012

Call Function from Stored Procedure

Hi All,

I'll admit that I'm not the greatest at stored procedure/functions but I want to learn as much as possible. So I have two questions:

1) I had VS2005 autogenerate a sqldatasource that created Select/Insert/Update stored procedures. When Updating a record and calling the stored procedure, I want to query another table (we'll call it tblBatchNo) that has only one record, Batchno. I want to put that current batchno into the Update statement and update the record with the current batchno. Can someone point me in the right direction? Remember that I'm still a beginner on this subject.

2) Can someone provide any links to online tutorials on t-sql?

Thanks in advance.

Curtis

Here's the best link I know of on How to Share Data Between Stored Procedures:http://www.sommarskog.se/share_data.html. Per the article, I recently converted some old procs into table variable values functions. ADO.NET reads a table variable just a table. Best of all, you can use the function from within another stored proc.

If you need info about table variables, try this link:http://www.odetocode.com/Articles/365.aspx.

HTH.

|||

Thanks! This will get me started in the right direction.

Curtis