Showing posts with label select. Show all posts
Showing posts with label select. Show all posts

Thursday, March 29, 2012

Calling Stored Procedure to get results into another stored procedure

I have a complex stored procedure which in the end, has a select statement and returns a number of rows... such as: Select * from Temp_Table.

I want to access these records in another stored procedure and do some maniulation on the rows, such as sum them or perform other calculations.

How can I access these rows via a select statement or just insert them into a temp table in the 2nd stored procedure?

Thanks so much

Stored Procedures can't be referenced in the FROM clause.

But you can use them as input to an INSERT statement.

Code Snippet

createtable #t1(a int, b int, c int)

insertinto #t1

exec dbo.myproc

|||

One way to do this is to create the temp table in the calling procedure and then load it in the called procedure:

ifobject_id('spy')isnotnulldropproc spy

go

createproc spy as

insert #x values(1)

return

go

ifobject_id('spx')isnotnulldropproc spx

go

createproc spx as

createtable #x(x1 int)

exec spy

select*from #x

return

go

exec spx

Ron Rice

|||

Thanks for the response...

I converted the Stored Proc to an inline table function. This seems to do the trick.

Tks

Tuesday, March 27, 2012

calling stored proc. from bcp

here's what I'm trying:
create procedure querytotext
as
select * from tablename
create function querytotext()
returns tables
as
return select * from tablename
bcp 'querytotext queryout filename.txt
bcp 'select querytotext()' queryout filename.txt
None of them working. bcp is calling neither stored procedure nor function.
Is it the limitation of bcp?Hi
Using double quotes around the query will help along with specifying the
database name for the procedure
bcp "EXEC mydb..querytotext" queryout filename.txt -T-c
John
try something like:
BCP "
"Raj" wrote:

> here's what I'm trying:
> create procedure querytotext
> as
> select * from tablename
> create function querytotext()
> returns tables
> as
> return select * from tablename
> bcp 'querytotext queryout filename.txt
> bcp 'select querytotext()' queryout filename.txt
> None of them working. bcp is calling neither stored procedure nor function
.
> Is it the limitation of bcp?
>
>

calling stored proc. from bcp

here's what I'm trying:
create procedure querytotext
as
select * from tablename
create function querytotext()
returns tables
as
return select * from tablename
bcp 'querytotext queryout filename.txt
bcp 'select querytotext()' queryout filename.txt
None of them working. bcp is calling neither stored procedure nor function.
Is it the limitation of bcp?Hi
Using double quotes around the query will help along with specifying the
database name for the procedure
bcp "EXEC mydb..querytotext" queryout filename.txt -T-c
John
try something like:
BCP "
"Raj" wrote:
> here's what I'm trying:
> create procedure querytotext
> as
> select * from tablename
> create function querytotext()
> returns tables
> as
> return select * from tablename
> bcp 'querytotext queryout filename.txt
> bcp 'select querytotext()' queryout filename.txt
> None of them working. bcp is calling neither stored procedure nor function.
> Is it the limitation of bcp?
>
>

Calling stored proc B from stored proc A

Hi all

I have about 5 stored procedures that, among other things, execute exactly the same SELECT statement

Instead of copying the SELECT statement 5 times, I'd like each stored proc to call a single stored proc that executes the SELECT statement and returns the resultset to the calling stored proc

The SELECT statement in question retrieves a single row from a table containing 10 columns.

Is there a way for a stored proc to call another stored proc and gain access to the resultset of the called stored proc?

I know about stored proc return values and about output parameters, but I think I am looking for something different.

ThanksYou can create a table variable and return it to the outer proc ... i assume thats what you are looking for

:)|||instead of procedure create a table-value udf|||If SQLServer 2000, use the @.table datatype
If SQLServer 7.0, create a temp table in proc 1 and populate it in proc 2 (just be aware of that proc 2 is gonna recompile each time its run)|||If it's Always just 1 row (are you sure) wht not pass back OUTPUT variables?|||Originally posted by Jonte
If SQLServer 2000, use the @.table datatype
If SQLServer 7.0, create a temp table in proc 1 and populate it in proc 2 (just be aware of that proc 2 is gonna recompile each time its run)

Thanks to Enigma, ms_sql_dba and Jonte. A table variable is exactly what I was searching for.|||Originally posted by Brett Kaiser
If it's Always just 1 row (are you sure) wht not pass back OUTPUT variables?

Hi

I was looking for a solution where I didnt have to declare 10+ output variables, or one that would work on occassions where there is more than 1 row returned

However, I understand that output variables are generally better for performance that using a table variable?|||Originally posted by mattkrevs
Hi

I was looking for a solution where I didnt have to declare 10+ output variables, or one that would work on occassions where there is more than 1 row returned

However, I understand that output variables are generally better for performance that using a table variable?

Well, obviously, if you had a table variable with 15 columns or you had 15 output parameters, then the 15 output parameters would have less overhead.

Oh, and don't use UDF's when you can use SP's. UDF don't get precompiled.|||Originally posted by mattkrevs
Hi

I was looking for a solution where I didnt have to declare 10+ output variables, or one that would work on occassions where there is more than 1 row returned

However, I understand that output variables are generally better for performance that using a table variable?

I like lazy...

But it seems misguided...you still have to code the local table variables anyway...

And in what instances will you get more than 1 row...

what would you do wiuth them...sounds like you need to make a decision anyway...why not do it in the sproc?|||Originally posted by beyond cool
Oh, and don't use UDF's when you can use SP's. UDF don't get precompiled.

Can you explain in more detail what you mean by that?|||Originally posted by Brett Kaiser
I like lazy...

But it seems misguided...you still have to code the local table variables anyway...

And in what instances will you get more than 1 row...

what would you do wiuth them...sounds like you need to make a decision anyway...why not do it in the sproc?

Hmmm. You know me too well. Yes its a bit lazy I guess. The stored proc I want to create and call checks for the existance of a row in a table and creates it if it doesnt find it.
Since the calling stored procs only needs info on 2 of the columns of the created row at present then I guess output params might be the best option.

I am interested in the table variable as it is a little more flexible and future proof as I can make all of the columns in the created row available to all calling stored procs.|||Originally posted by mattkrevs
Hmmm. You know me too well. Yes its a bit lazy I guess. The stored proc I want to create and call checks for the existance of a row in a table and creates it if it doesnt find it.
Since the calling stored procs only needs info on 2 of the columns of the created row at present then I guess output params might be the best option.

I am interested in the table variable as it is a little more flexible and future proof as I can make all of the columns in the created row available to all calling stored procs.

Brett - I think I'll go with your output parameters option. I found 2 problems with using table variables

1. I didnt realise you had to fully declare table variables including the table structure. Kind of defeats the purpose of 'lazy' coding

2. I tried this and I got the error "EXECUTE cannot be used as a source when inserting into a table variable." so it looks like it doesnt work anyway. I found other posters had the same problem and they ended up using temp tables instead.|||Hey, don't get me wrong...lazy is a good thing...

It means you're trying to find more effecient ways to do something, rather than the long way around...

Can you posted what you tried though? I'm curious as to why it didn't work for you...|||I kinda like the concept of lazy (http://www.lazydba.com/lazydba_info.html) coding.
Its fun and its challenging!!!!

I believe the laziest i've encountered has to be this one (http://www.dbforums.com/showthread.php?threadid=975995)|||Good site, Enigma

Thursday, March 22, 2012

Calling Oracle Stored Proc from SqlServer

I am trying to call an Oracle stored procedure from SqlServer. I have tried
both the MS and Oracle OLE DB Providers.
I can select records from Oracle and I can insert records to Oracle. The
stored proc call dies.
The interesting part in this is that I can write a VB script that calls the
stored procedure from the server that the SqlServer instance is running on
and it is able to execute the proc. The VB script uses Oracle's OLE DB
Provider.
We are using SqlServer 2000 and Oracle 9.2.0.6
I am sure that there is something setup incorrectly with SqlServer.
Any ideas
RSLHimm?
So i think u must use sp_OACreate, sp_OAMethod, sp_OADestroy methods in sql
server procedures or triggers.
First, make a dll for oracle actions. And call dll in sql server t-sql with
those method.
Message posted via http://www.droptable.comsql

Calling Oracle Stored Proc from SqlServer

I am trying to call an Oracle stored procedure from SqlServer. I have tried
both the MS and Oracle OLE DB Providers.
I can select records from Oracle and I can insert records to Oracle. The
stored proc call dies.
The interesting part in this is that I can write a VB script that calls the
stored procedure from the server that the SqlServer instance is running on
and it is able to execute the proc. The VB script uses Oracle's OLE DB
Provider.
We are using SqlServer 2000 and Oracle 9.2.0.6
I am sure that there is something setup incorrectly with SqlServer.
Any ideas
RSLHimm?
So i think u must use sp_OACreate, sp_OAMethod, sp_OADestroy methods in sql
server procedures or triggers.
First, make a dll for oracle actions. And call dll in sql server t-sql with
those method.
--
Message posted via http://www.sqlmonster.com

Calling Oracle Stored Proc from SqlServer

I am trying to call an Oracle stored procedure from SqlServer. I have tried
both the MS and Oracle OLE DB Providers.
I can select records from Oracle and I can insert records to Oracle. The
stored proc call dies.
The interesting part in this is that I can write a VB script that calls the
stored procedure from the server that the SqlServer instance is running on
and it is able to execute the proc. The VB script uses Oracle's OLE DB
Provider.
We are using SqlServer 2000 and Oracle 9.2.0.6
I am sure that there is something setup incorrectly with SqlServer.
Any ideas
RSL
Himm?
So i think u must use sp_OACreate, sp_OAMethod, sp_OADestroy methods in sql
server procedures or triggers.
First, make a dll for oracle actions. And call dll in sql server t-sql with
those method.
Message posted via http://www.droptable.com

Calling one Sp from Another

Hi,
I have a stored procedure (say sp_1) that returns a number.
A simplified form of sp_1 could be
Create procedure sp_1 as
Select 1
Go
Now, I would like to call sp_1 from another sp (say sp_2)
and store the value in a variable. I tried this
Create procedure sp_2 as
Declare @.xyz as integer
Set @.xyz = (exec sp_1)
This does not work.
Could somebody point me the mistake?
Thanks,
RamThis is a multi-part message in MIME format.
--=_NextPart_000_01C5_01C3CDFB.55950220
Content-Type: text/plain;
charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
Try;
create proc sp1
( @.parm int output)
as
select @.parm = 1
go
create proc sp2
as
declare @.p as int
exec sp1 @.p output
go
Tom
---
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinnaclepublishing.com/sql
"Ram" <anonymous@.discussions.microsoft.com> wrote in message
news:04b401c3ce22$4b1c9480$a001280a@.phx.gbl...
Hi,
I have a stored procedure (say sp_1) that returns a number.
A simplified form of sp_1 could be
Create procedure sp_1 as
Select 1
Go
Now, I would like to call sp_1 from another sp (say sp_2)
and store the value in a variable. I tried this
Create procedure sp_2 as
Declare @.xyz as integer
Set @.xyz = (exec sp_1)
This does not work.
Could somebody point me the mistake?
Thanks,
Ram
--=_NextPart_000_01C5_01C3CDFB.55950220
Content-Type: text/html;
charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
&

Try;
create proc sp1
( @.parm int =output)
as
select @.parm =3D 1
go
create proc sp2
as
declare @.p as int
exec sp1 @.p output
go
-- Tom
---T=homas A. Moreau, BSc, PhD, MCSE, MCDBASQL Server MVPColumnist, SQL =Server ProfessionalToronto, ON Canadahttp://www.pinnaclepublishing.com/sql">www.pinnaclepublishing.com=/sql
"Ram" wrote in message news:04b401c3ce22$4b=1c9480$a001280a@.phx.gbl...Hi,I have a stored procedure (say sp_1) that returns a number.A =simplified form of sp_1 could beCreate procedure sp_1 asSelect =1GoNow, I would like to call sp_1 from another sp (say sp_2) and store the =value in a variable. I tried thisCreate procedure sp_2 as Declare @.xyz =as integerSet @.xyz =3D (exec sp_1)This does not =work.Could somebody point me the =mistake?Thanks,Ram

--=_NextPart_000_01C5_01C3CDFB.55950220--|||Hi,
Create a Linked server from server 2 and then call the SP_1
Thanks
Hari
MCDBA
"Ram" <anonymous@.discussions.microsoft.com> wrote in message
news:04b401c3ce22$4b1c9480$a001280a@.phx.gbl...
> Hi,
> I have a stored procedure (say sp_1) that returns a number.
> A simplified form of sp_1 could be
> Create procedure sp_1 as
> Select 1
> Go
> Now, I would like to call sp_1 from another sp (say sp_2)
> and store the value in a variable. I tried this
> Create procedure sp_2 as
> Declare @.xyz as integer
> Set @.xyz = (exec sp_1)
> This does not work.
> Could somebody point me the mistake?
>
> Thanks,
> Ram
>|||This is a multi-part message in MIME format.
--=_NextPart_000_01F3_01C3CDFC.4D684E80
Content-Type: text/plain;
charset="Windows-1252"
Content-Transfer-Encoding: 7bit
Why would you need a linked server for this?
--
Tom
---
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinnaclepublishing.com/sql
"Hari Prasad" <hari_prasad_k@.hotmail.com> wrote in message
news:#aYouVizDHA.2308@.TK2MSFTNGP11.phx.gbl...
Hi,
Create a Linked server from server 2 and then call the SP_1
Thanks
Hari
MCDBA
"Ram" <anonymous@.discussions.microsoft.com> wrote in message
news:04b401c3ce22$4b1c9480$a001280a@.phx.gbl...
> Hi,
> I have a stored procedure (say sp_1) that returns a number.
> A simplified form of sp_1 could be
> Create procedure sp_1 as
> Select 1
> Go
> Now, I would like to call sp_1 from another sp (say sp_2)
> and store the value in a variable. I tried this
> Create procedure sp_2 as
> Declare @.xyz as integer
> Set @.xyz = (exec sp_1)
> This does not work.
> Could somebody point me the mistake?
>
> Thanks,
> Ram
>
--=_NextPart_000_01F3_01C3CDFC.4D684E80
Content-Type: text/html;
charset="Windows-1252"
Content-Transfer-Encoding: quoted-printable
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
&

Why would you need a linked server for =this?
-- Tom
---T=homas A. Moreau, BSc, PhD, MCSE, MCDBASQL Server MVPColumnist, SQL =Server ProfessionalToronto, ON Canadahttp://www.pinnaclepublishing.com/sql">www.pinnaclepublishing.com=/sql
"Hari Prasad" Hi,> I have a stored procedure (say sp_1) that returns a =number.> A simplified form of sp_1 could be>> Create procedure sp_1 =as> Select 1> Go>> Now, I would like to call =sp_1 from another sp (say sp_2)> and store the value in a variable. I =tried this>> Create procedure sp_2 as> Declare @.xyz as integer> Set @.xyz =3D (exec sp_1)>> This does not work.>> Could somebody point me the mistake?>>> Thanks,> Ram>

--=_NextPart_000_01F3_01C3CDFC.4D684E80--|||Hi,
You can use output parameter.
create procedure sp_1 @.x int output
as
select @.x=1
go
-- executing above sp.
declare @.xx int
exec sp_1 @.xx output
print @.xx
--
- Vishal|||This is a multi-part message in MIME format.
--=_NextPart_000_00B2_01C3CE55.AA81C840
Content-Type: text/plain;
charset="Windows-1252"
Content-Transfer-Encoding: quoted-printable
Sorry Tom, you are correct, I misunderstood SP2 as server 2.
Thanks
Hari
MCDBA
"Tom Moreau" <tom@.dont.spam.me.cips.ca> wrote in message =news:#CBH8YizDHA.1744@.TK2MSFTNGP12.phx.gbl...
Why would you need a linked server for this?
-- Tom
---
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinnaclepublishing.com/sql
"Hari Prasad" <hari_prasad_k@.hotmail.com> wrote in message =news:#aYouVizDHA.2308@.TK2MSFTNGP11.phx.gbl...
Hi,
Create a Linked server from server 2 and then call the SP_1
Thanks
Hari
MCDBA
"Ram" <anonymous@.discussions.microsoft.com> wrote in message
news:04b401c3ce22$4b1c9480$a001280a@.phx.gbl...
> Hi,
> I have a stored procedure (say sp_1) that returns a number.
> A simplified form of sp_1 could be
>
> Create procedure sp_1 as
> Select 1
> Go
>
> Now, I would like to call sp_1 from another sp (say sp_2)
> and store the value in a variable. I tried this
>
> Create procedure sp_2 as
> Declare @.xyz as integer
> Set @.xyz =3D (exec sp_1)
>
> This does not work.
>
> Could somebody point me the mistake?
>
>
> Thanks,
> Ram
>
--=_NextPart_000_00B2_01C3CE55.AA81C840
Content-Type: text/html;
charset="Windows-1252"
Content-Transfer-Encoding: quoted-printable
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
&

Sorry Tom, you are correct, I =misunderstood SP2 as server 2.
Thanks
Hari
MCDBA
"Tom Moreau" = wrote in message news:#CBH8YizDHA.1744=@.TK2MSFTNGP12.phx.gbl...
Why would you need a linked server =for this?
-- Tom

=---T=homas A. Moreau, BSc, PhD, MCSE, MCDBASQL Server MVPColumnist, SQL =Server ProfessionalToronto, ON Canadahttp://www.pinnaclepublishing.com/sql">www.pinnaclepublishing.com=/sql


"Hari Prasad" Hi,> I have a stored procedure (say sp_1) that returns a number.> A simplified form of sp_1 could be>> =Create procedure sp_1 as> Select 1> Go>> Now, I =would like to call sp_1 from another sp (say sp_2)> and store the =value in a variable. I tried this>> Create procedure sp_2 =as> Declare @.xyz as integer> Set @.xyz =3D (exec =sp_1)>> This does not work.>> Could somebody point me the mistake?>>> Thanks,> Ram>

--=_NextPart_000_00B2_01C3CE55.AA81C840--|||This will not work
> Create procedure sp_2 as
> Declare @.xyz as integer
> Set @.xyz = (exec sp_1)
because the sproc sp_1 will get you the return value.
You should always have a
RETURN some_integer
at the end of each sproc to inform the caller about the status.
so
> Create procedure sp_1 as
> Select 1
> RETURN 20 << added this
> Go
Then
> Declare @.xyz as integer
> EXEC @.xyz = (exec sp_1)
@.xyz will be 20 and not 1.
There is another way besides output params you can use to store the
resultset from the sproc:
CREATE PROC sp_1
AS
SELECT 'ABCD', 10
UNION
SELECT 'EFGH', 20
RETURN @.@.ERROR
GO
CREATE TABLE TAB1 (F1 VARCHAR(10), F2 INT)
GO
-- **************************
INSERT INTO TAB1
EXEC sp_1
GO
-- **************************
SELECT * FROM TAB1
GO
"Ram" <anonymous@.discussions.microsoft.com> wrote in message
news:04b401c3ce22$4b1c9480$a001280a@.phx.gbl...
> Hi,
> I have a stored procedure (say sp_1) that returns a number.
> A simplified form of sp_1 could be
> Create procedure sp_1 as
> Select 1
> Go
> Now, I would like to call sp_1 from another sp (say sp_2)
> and store the value in a variable. I tried this
> Create procedure sp_2 as
> Declare @.xyz as integer
> Set @.xyz = (exec sp_1)
> This does not work.
> Could somebody point me the mistake?
>
> Thanks,
> Ram
>|||Thanks for the solutions Daniel, Tom and Vishal. It worked.
Ram
>--Original Message--
> Hi,
> You can use output parameter.
> create procedure sp_1 @.x int output
> as
> select @.x=1
> go
> -- executing above sp.
> declare @.xx int
> exec sp_1 @.xx output
> print @.xx
> --
> - Vishal
>
>.
>sql

Calling Joe Celko (or anyone else that knows)

(I think you were the one that posted this)
Someone asked how to count two different things in one select statement.
I had never seen it before and I was deeply impressed.
A coworker is asking me how to do two different counts grouped by different
things...
Some column called IVP can be 1, 0 or NULL. He wants to execute a statement
that generates a one-line result set of counts that looks like this
| 1Count | 0Count | NullCount |
| 47 | 23 | 5 |
Something like this:
SELECT
COUNT([?]) AS 1Count,
COUNT([?]) AS 0Count,
COUNT([?]) AS NullCount
FROM TheTable
-- GROUP BY [?] -- is this even required?
Peace & happy computing,
Mike Labosh, MCSD
"When you kill a man, you're a murderer.
Kill many, and you're a conqueror.
Kill them all and you're a god." -- Dave MustaneSELECT
SUM (CASE WHEN foo = 0 THEN 1 ELSE 0 END) AS tally_0,
SUM (CASE WHEN foo = 1 THEN 1 ELSE 0 END) AS tally_1,
SUM (CASE WHEN foo IS NULL THEN 1 ELSE 0 END) AS tally_null,
FROM TheTable;|||Try:
select
sum(case when c1 = 1 then 1 else 0 end) as count_1,
sum(case when c1 = 0 then 1 else 0 end) as count_0,
sum(case when c1 is null then 1 else 0 end) as count_null
from
t1
AMB
"Mike Labosh" wrote:

> (I think you were the one that posted this)
> Someone asked how to count two different things in one select statement.
> I had never seen it before and I was deeply impressed.
> A coworker is asking me how to do two different counts grouped by differen
t
> things...
> Some column called IVP can be 1, 0 or NULL. He wants to execute a stateme
nt
> that generates a one-line result set of counts that looks like this
> | 1Count | 0Count | NullCount |
> | 47 | 23 | 5 |
> Something like this:
> SELECT
> COUNT([?]) AS 1Count,
> COUNT([?]) AS 0Count,
> COUNT([?]) AS NullCount
> FROM TheTable
> -- GROUP BY [?] -- is this even required?
> --
> Peace & happy computing,
> Mike Labosh, MCSD
> "When you kill a man, you're a murderer.
> Kill many, and you're a conqueror.
> Kill them all and you're a god." -- Dave Mustane
>
>|||Thanks everyone; the coworker was quite impressed.
Peace & happy computing,
Mike Labosh, MCSD
"When you kill a man, you're a murderer.
Kill many, and you're a conquerer.
Kill them all and you're a god." -- Dave Mustane

calling javascript on OnSelectedIndexChanged of a drop downlistbox

I have a dropdownlist and a text box.

Once i select the item on a dropdownlist, the control should skip to text box.

Here is the code and i get the error.

'onFocus' is not a member of 'ASP.test_aspx'.

can u plz help me out.

<htmlxmlns="http://www.w3.org/1999/xhtml">

<headrunat="server">

<title>Untitled Page</title>

<scriptlanguage="javascript">

function onFocus()

{

var control = document.getElementById("TextBox1");

if( control != null ) control.focus();

}

</script>

</head>

<body>

<formid="form1"runat="server">

<div>

<asp:DropDownListID="DropDownList1"runat="server"Width="161px"OnSelectedIndexChanged="onFocus()">

<asp:ListItem>Javed</asp:ListItem>

<asp:ListItem>Abid</asp:ListItem>

<asp:ListItem>sajid</asp:ListItem>

<asp:ListItem></asp:ListItem>

</asp:DropDownList>

<asp:TextBoxID="TextBox1"runat="server"></asp:TextBox></div>

</form>

</body>

</html>

The reason you are getting this type of error is because you try to associate (link) JS function with ASP event. when you declare event such as OnSelectedIndexChanged ASP searchs the code behind or C#/VB section for a handler to invoke once this event fires.

A very simple way to diffrentiate between HTML DOM events and ASP events is the case. Note that ASP is always MixCase.

sql

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)
>
>

Monday, March 19, 2012

Calling All T-SQL Gods & Goddesses

Hi

I'm having trouble with the script below that it just won't do a
correct ORDER BY for a date field.

When executing the two SELECT TOP statements on their own the records
are sorted correctly but when wrapped in the main statement, the ORDER
BY is just ignored. Tried to play around with the script but with no
luck. Script is for paging, in this case, select all records meeting
criteria, order and select Top 25 to display on first page. Any
questions, please don't hesitate contacting me.

Thanks very much to anyone who's having a look at this!

Martin

SELECT COALESCE((i2b_contact.Firstname + CHAR(32) +
i2b_contact.Lastname),i2b_company.CompanyName) AS CName,
i2b_keytransactionlog.KeyTransactionLogID, i2b_key.KeyCode,
(i2b_address.Address1) AS PropertyAddress,
A.ProgUserName AS ProgUserName,
CONVERT (varchar(10), i2b_keytransactionlog.TransactionDate, 104 ) AS
TransactionDate,
CONVERT(varchar(10),i2b_keytransactionlog.ReturnBy Date,104) AS
ReturnByDate
FROM i2b_keytransactionlog
LEFT JOIN i2b_contact ON (i2b_keytransactionlog.EntityID =
i2b_contact.ContactID AND i2b_keytransactionlog.IsContact = 1)
LEFT JOIN i2b_company ON (i2b_keytransactionlog.EntityID =
i2b_company.CompanyID AND i2b_keytransactionlog.IsContact = 0)
JOIN i2b_key ON (i2b_keytransactionlog.KeyID = i2b_key.KeyID)
JOIN i2b_property on (i2b_key.PropertyID = i2b_property.PropertyID)
JOIN i2b_address ON (i2b_property.AddressID = i2b_address.AddressID)
JOIN i2b_proguser AS A ON (i2b_keytransactionlog.ProgUserID =
A.ProgUserID)
WHERE KeyTransactionLogID IN(SELECT TOP 25 KeyTransactionLogID FROM
i2b_keytransactionlog
LEFT JOIN i2b_contact ON (i2b_keytransactionlog.EntityID =
i2b_contact.ContactID AND i2b_keytransactionlog.IsContact = 1)
LEFT JOIN i2b_company ON (i2b_keytransactionlog.EntityID =
i2b_company.CompanyID AND i2b_keytransactionlog.IsContact = 0)
JOIN i2b_key ON (i2b_keytransactionlog.KeyID = i2b_key.KeyID)
JOIN i2b_property on (i2b_key.PropertyID = i2b_property.PropertyID)
JOIN i2b_address ON (i2b_property.AddressID = i2b_address.AddressID)
JOIN i2b_proguser AS A ON (i2b_keytransactionlog.ProgUserID =
A.ProgUserID)
WHERE i2b_keytransactionlog.ProgClientID = 1 AND
i2b_keytransactionlog.ProgUserID = 3 AND KeyTransactionLogID NOT IN
(SELECT TOP 0 KeyTransactionLogID FROM i2b_keytransactionlog
LEFT JOIN i2b_contact ON (i2b_keytransactionlog.EntityID =
i2b_contact.ContactID AND i2b_keytransactionlog.IsContact = 1)
LEFT JOIN i2b_company ON (i2b_keytransactionlog.EntityID =
i2b_company.CompanyID AND i2b_keytransactionlog.IsContact = 0)
JOIN i2b_key ON (i2b_keytransactionlog.KeyID = i2b_key.KeyID)
JOIN i2b_property on (i2b_key.PropertyID = i2b_property.PropertyID)
JOIN i2b_address ON (i2b_property.AddressID = i2b_address.AddressID)
JOIN i2b_proguser AS A ON (i2b_keytransactionlog.ProgUserID =
A.ProgUserID)
WHERE i2b_keytransactionlog.ProgClientID = 1 AND
i2b_keytransactionlog.ProgUserID = 3 ORDER BY ReturnByDate DESC)
ORDER BY ReturnByDate DESC)
ORDER BY ReturnByDate DESCOn 29 May 2004 12:19:20 -0700, Martin wrote:

>Hi
>I'm having trouble with the script below that it just won't do a
>correct ORDER BY for a date field.
>When executing the two SELECT TOP statements on their own the records
>are sorted correctly but when wrapped in the main statement, the ORDER
>BY is just ignored. Tried to play around with the script but with no
>luck. Script is for paging, in this case, select all records meeting
>criteria, order and select Top 25 to display on first page. Any
>questions, please don't hesitate contacting me.
>Thanks very much to anyone who's having a look at this!
>Martin
>SELECT COALESCE((i2b_contact.Firstname + CHAR(32) +
>i2b_contact.Lastname),i2b_company.CompanyName) AS CName,
>i2b_keytransactionlog.KeyTransactionLogID, i2b_key.KeyCode,
>(i2b_address.Address1) AS PropertyAddress,
>A.ProgUserName AS ProgUserName,
>CONVERT (varchar(10), i2b_keytransactionlog.TransactionDate, 104 ) AS
>TransactionDate,
>CONVERT(varchar(10),i2b_keytransactionlog.ReturnBy Date,104) AS
>ReturnByDate
> FROM i2b_keytransactionlog
>LEFT JOIN i2b_contact ON (i2b_keytransactionlog.EntityID =
>i2b_contact.ContactID AND i2b_keytransactionlog.IsContact = 1)
>LEFT JOIN i2b_company ON (i2b_keytransactionlog.EntityID =
>i2b_company.CompanyID AND i2b_keytransactionlog.IsContact = 0)
>JOIN i2b_key ON (i2b_keytransactionlog.KeyID = i2b_key.KeyID)
>JOIN i2b_property on (i2b_key.PropertyID = i2b_property.PropertyID)
>JOIN i2b_address ON (i2b_property.AddressID = i2b_address.AddressID)
>JOIN i2b_proguser AS A ON (i2b_keytransactionlog.ProgUserID =
>A.ProgUserID)
>WHERE KeyTransactionLogID IN(SELECT TOP 25 KeyTransactionLogID FROM
>i2b_keytransactionlog
>LEFT JOIN i2b_contact ON (i2b_keytransactionlog.EntityID =
>i2b_contact.ContactID AND i2b_keytransactionlog.IsContact = 1)
>LEFT JOIN i2b_company ON (i2b_keytransactionlog.EntityID =
>i2b_company.CompanyID AND i2b_keytransactionlog.IsContact = 0)
>JOIN i2b_key ON (i2b_keytransactionlog.KeyID = i2b_key.KeyID)
>JOIN i2b_property on (i2b_key.PropertyID = i2b_property.PropertyID)
>JOIN i2b_address ON (i2b_property.AddressID = i2b_address.AddressID)
>JOIN i2b_proguser AS A ON (i2b_keytransactionlog.ProgUserID =
>A.ProgUserID)
>WHERE i2b_keytransactionlog.ProgClientID = 1 AND
>i2b_keytransactionlog.ProgUserID = 3 AND KeyTransactionLogID NOT IN
> (SELECT TOP 0 KeyTransactionLogID FROM i2b_keytransactionlog
>LEFT JOIN i2b_contact ON (i2b_keytransactionlog.EntityID =
>i2b_contact.ContactID AND i2b_keytransactionlog.IsContact = 1)
>LEFT JOIN i2b_company ON (i2b_keytransactionlog.EntityID =
>i2b_company.CompanyID AND i2b_keytransactionlog.IsContact = 0)
>JOIN i2b_key ON (i2b_keytransactionlog.KeyID = i2b_key.KeyID)
>JOIN i2b_property on (i2b_key.PropertyID = i2b_property.PropertyID)
>JOIN i2b_address ON (i2b_property.AddressID = i2b_address.AddressID)
>JOIN i2b_proguser AS A ON (i2b_keytransactionlog.ProgUserID =
>A.ProgUserID)
>WHERE i2b_keytransactionlog.ProgClientID = 1 AND
>i2b_keytransactionlog.ProgUserID = 3 ORDER BY ReturnByDate DESC)
> ORDER BY ReturnByDate DESC)
> ORDER BY ReturnByDate DESC

Hi Martin,

I'm not entirely sure why you would use TOP 0 for the NOT IN subquery, but
that's not the cause of the problem you post about.

The ANSI standard for SQL allows only columns appearing in the SELECT list
in the ORDER BY clause. The rationale being that first, the query gets
executed and the result set is determined; the sorting is a seperate,
final stage. ANSI SQL allows things as ORDER BY 3 (3 being the third
column in the SELECT LIST) or SELECT MyColumn AS ColumnAlias ... ORDER BY
ColumnAlias.

MS SQL Server expands on this standard. With MS SQL Server, you can ORDER
BY on a column not in the SELECT list. If you use a column name that is
not an alias in the column list, SQL Server will try to locate a column
with that name in one of the tables used in the query and use that for
sorting.

Before I get back to your problem, run the following script. It will
clearly show that SQL Server will first attempt to resolve names in the
ORDER BY clause following ANSI standard before looking at the columns that
make up the data.

CREATE TABLE testtab (a int, b int)
go
INSERT testtab (a, b) SELECT 1, 20
INSERT testtab (a, b) SELECT 2, 10
go
SELECT b
FROM testtab
ORDER BY a
go
SELECT b AS a
FROM testtab
ORDER BY a
go
SELECT b AS a, a AS b
FROM testtab
ORDER BY a
go
DROP TABLE testtab
go

In the first query, no column "a" is in the SELECT list, so SQL Server
will sort on the column a in the table. In the second query, the SELECT
list has a column aliased as "a", so this is used for sorting. In the
third query, the column a itself is used in the select list; aliases are
disregarded and sorting is done on the contents of a.

Now back to your real problem. I'll show you the parts that cause the
unexpected ordering:

>SELECT (...)
> (...)
>CONVERT(varchar(10),i2b_keytransactionlog.ReturnBy Date,104) AS
>ReturnByDate
> (...)
> ORDER BY ReturnByDate DESC

The column ReturnByDate is not used in the SELECT list (the results of a
function are not cosidered equal to the column itself). There is however
an alias ReturnByDate, so there's no need to get back to the data in the
table either - the aliased column in the result set is used. This column
is the output of a CONVERT function call. It's varchar(10), therefor the
sorting will be done by alphabet, descending. "23-04-2003" will go before
"06-05-2004".

The fix? Either use something else as an alias ([Return By Date], for
example) or use ORDER BY CONVERT(datetime, ReturnByDate).

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)

Calling a UDF that returns a table from within a select statement

I have a UDF that returns a table data type by recursion. The UDF takes a
two input parameters. Can I call the UDF within a Select statement?
i.e.
SELECT dbo.GetTable(col2,1)
FROM table
"Tadwick" <Tadwick@.discussions.microsoft.com> wrote in message
news:DA800CC3-27DD-4003-B337-8B4C990B3A7E@.microsoft.com...
>I have a UDF that returns a table data type by recursion. The UDF takes a
> two input parameters. Can I call the UDF within a Select statement?
> i.e.
> SELECT dbo.GetTable(col2,1)
> FROM table
If you are passing a column value into the UDF you must use the new (SQL
2005) APPLY operator
SELECT t.whatever, gt.*
FROM table t
CROSS APPLY dbo.GetTable(col2,1) gt
David
|||David,
Does this apply only to CLR functions?
-- Bill
"David Browne" <davidbaxterbrowne no potted meat@.hotmail.com> wrote in
message news:eG9QJ7JTHHA.3428@.TK2MSFTNGP04.phx.gbl...
>
> "Tadwick" <Tadwick@.discussions.microsoft.com> wrote in message
> news:DA800CC3-27DD-4003-B337-8B4C990B3A7E@.microsoft.com...
> If you are passing a column value into the UDF you must use the new (SQL
> 2005) APPLY operator
> SELECT t.whatever, gt.*
> FROM table t
> CROSS APPLY dbo.GetTable(col2,1) gt
> David
>
|||Thanks,
So, is there a method or workaround for doing this in SQL Server 2000?
"David Browne" wrote:

>
> "Tadwick" <Tadwick@.discussions.microsoft.com> wrote in message
> news:DA800CC3-27DD-4003-B337-8B4C990B3A7E@.microsoft.com...
> If you are passing a column value into the UDF you must use the new (SQL
> 2005) APPLY operator
> SELECT t.whatever, gt.*
> FROM table t
> CROSS APPLY dbo.GetTable(col2,1) gt
> David
>
>
|||"Tadwick" <Tadwick@.discussions.microsoft.com> wrote in message
news:C5C4903C-A9CA-4C80-8B8D-85E0C7C9A4AD@.microsoft.com...
> Thanks,
> So, is there a method or workaround for doing this in SQL Server 2000?
>
Not in the general case (thus the need to extend SQL). But if you have only
a few values for col2, you can perhaps use a cursor and a temp table to
construct the results.
David
|||"AlterEgo" <alterego55@.dslextreme.com> wrote in message
news:e7iqBLKTHHA.4756@.TK2MSFTNGP06.phx.gbl...
> David,
> Does this apply only to CLR functions?
>
No. All Table-Valued UDF's/.
David

Calling a UDF that returns a table from within a select statement

I have a UDF that returns a table data type by recursion. The UDF takes a
two input parameters. Can I call the UDF within a Select statement?
i.e.
SELECT dbo.GetTable(col2,1)
FROM table"Tadwick" <Tadwick@.discussions.microsoft.com> wrote in message
news:DA800CC3-27DD-4003-B337-8B4C990B3A7E@.microsoft.com...
>I have a UDF that returns a table data type by recursion. The UDF takes a
> two input parameters. Can I call the UDF within a Select statement?
> i.e.
> SELECT dbo.GetTable(col2,1)
> FROM table
If you are passing a column value into the UDF you must use the new (SQL
2005) APPLY operator
SELECT t.whatever, gt.*
FROM table t
CROSS APPLY dbo.GetTable(col2,1) gt
David|||David,
Does this apply only to CLR functions?
-- Bill
"David Browne" <davidbaxterbrowne no potted meat@.hotmail.com> wrote in
message news:eG9QJ7JTHHA.3428@.TK2MSFTNGP04.phx.gbl...
>
> "Tadwick" <Tadwick@.discussions.microsoft.com> wrote in message
> news:DA800CC3-27DD-4003-B337-8B4C990B3A7E@.microsoft.com...
>>I have a UDF that returns a table data type by recursion. The UDF takes a
>> two input parameters. Can I call the UDF within a Select statement?
>> i.e.
>> SELECT dbo.GetTable(col2,1)
>> FROM table
> If you are passing a column value into the UDF you must use the new (SQL
> 2005) APPLY operator
> SELECT t.whatever, gt.*
> FROM table t
> CROSS APPLY dbo.GetTable(col2,1) gt
> David
>|||Thanks,
So, is there a method or workaround for doing this in SQL Server 2000?
"David Browne" wrote:
>
> "Tadwick" <Tadwick@.discussions.microsoft.com> wrote in message
> news:DA800CC3-27DD-4003-B337-8B4C990B3A7E@.microsoft.com...
> >I have a UDF that returns a table data type by recursion. The UDF takes a
> > two input parameters. Can I call the UDF within a Select statement?
> >
> > i.e.
> >
> > SELECT dbo.GetTable(col2,1)
> > FROM table
> If you are passing a column value into the UDF you must use the new (SQL
> 2005) APPLY operator
> SELECT t.whatever, gt.*
> FROM table t
> CROSS APPLY dbo.GetTable(col2,1) gt
> David
>
>|||"Tadwick" <Tadwick@.discussions.microsoft.com> wrote in message
news:C5C4903C-A9CA-4C80-8B8D-85E0C7C9A4AD@.microsoft.com...
> Thanks,
> So, is there a method or workaround for doing this in SQL Server 2000?
>
Not in the general case (thus the need to extend SQL). But if you have only
a few values for col2, you can perhaps use a cursor and a temp table to
construct the results.
David|||"AlterEgo" <alterego55@.dslextreme.com> wrote in message
news:e7iqBLKTHHA.4756@.TK2MSFTNGP06.phx.gbl...
> David,
> Does this apply only to CLR functions?
>
No. All Table-Valued UDF's/.
David

Calling a UDF that returns a table from within a select statement

I have a UDF that returns a table data type by recursion. The UDF takes a
two input parameters. Can I call the UDF within a Select statement?
i.e.
SELECT dbo.GetTable(col2,1)
FROM table"Tadwick" <Tadwick@.discussions.microsoft.com> wrote in message
news:DA800CC3-27DD-4003-B337-8B4C990B3A7E@.microsoft.com...
>I have a UDF that returns a table data type by recursion. The UDF takes a
> two input parameters. Can I call the UDF within a Select statement?
> i.e.
> SELECT dbo.GetTable(col2,1)
> FROM table
If you are passing a column value into the UDF you must use the new (SQL
2005) APPLY operator
SELECT t.whatever, gt.*
FROM table t
CROSS APPLY dbo.GetTable(col2,1) gt
David|||David,
Does this apply only to CLR functions?
-- Bill
"David Browne" <davidbaxterbrowne no potted meat@.hotmail.com> wrote in
message news:eG9QJ7JTHHA.3428@.TK2MSFTNGP04.phx.gbl...
>
> "Tadwick" <Tadwick@.discussions.microsoft.com> wrote in message
> news:DA800CC3-27DD-4003-B337-8B4C990B3A7E@.microsoft.com...
> If you are passing a column value into the UDF you must use the new (SQL
> 2005) APPLY operator
> SELECT t.whatever, gt.*
> FROM table t
> CROSS APPLY dbo.GetTable(col2,1) gt
> David
>|||"AlterEgo" <alterego55@.dslextreme.com> wrote in message
news:e7iqBLKTHHA.4756@.TK2MSFTNGP06.phx.gbl...
> David,
> Does this apply only to CLR functions?
>
No. All Table-Valued UDF's/.
David

Sunday, March 11, 2012

calling a procedure from another procedure

Maybe this isn't possible, but I'm trying to figure out how to call a procedure in a select statement where I can pass a new id each record found. Here is the procedure code that returns the desired results for any given ID:

CREATE PROCEDURE proc_amEnrollmentTrackingDetailGet_cst
@.syStudentID INTEGER
AS

DECLARE
@.SATACT DATETIME,
@.HSTranscript DATETIME,
@.AcceptLetter DATETIME,
@.FAFSA DATETIME,
@.FinAidApp DATETIME

--Get the last DateDue for each document type

SELECT
@.SATACT = CASE WHEN cmDocTypeID IN (81,110) THEN DateDue END,
@.HSTranscript = CASE WHEN cmDocTypeID IN (83) THEN DateDue END,
@.AcceptLetter = CASE WHEN cmDocTypeID IN (126) THEN DateDue END,
@.FAFSA = CASE WHEN cmDocTypeID IN (150) THEN DateDue END,
@.FinAidApp = CASE WHEN cmDocTypeID IN (155) THEN DateDue END
FROM
cmDocument (NOLOCK)
WHERE
syStudentID = @.syStudentID
ORDER BY
cmDocTypeID, DateDue

-- Return the results

SELECT
S.syStudentID,
S.StuNum,
@.SATACT AS SATACT,
@.HSTranscript AS HSTranscript,
@.AcceptLetter AS AcceptLetter,
@.FAFSA AS FAFSA,
@.FinAidApp AS FinAidApp,
S.FirstName,
S.LastName
FROM
syStudent S (NOLOCK)

WHERE S.syStudentID = @.syStudentID
GO

Now maybe there is a better way to do this, but what I want to do is to call the above procedure and have it return a row for every ID in the following code:

SELECT DISTINCT
S.syStudentID
FROM
syStudent S (NOLOCK)
JOIN cmActivity_vw A (NOLOCK)
ON A.syStudentID = S.syStudentID
AND A.cmTemplateID IN (16,195,283,290,291) --Application received
WHERE
S.StartDate BETWEEN '5/1/07' AND '9/1/07' -- Expected Start Date
AND S.amPrevEducID = 1 --High School Grad
AND S.syCampusID = 5 --Main Campus

Create a table valued function instead of a procedure.

See SQL Server 2005 Books Online topics:
CREATE FUNCTION (Transact-SQL)
http://msdn2.microsoft.com/en-us/library/ms186755.aspx

Using APPLY
http://msdn2.microsoft.com/en-us/library/ms175156.aspx

|||

Why do you even need a stored procedure? Why not merely use a larger query, e.g.,
SELECT
S.syStudentID,
S.StuNum,
CASE WHEN cmDocTypeID IN (81,110) THEN DateDue END as SATACT,
CASE WHEN cmDocTypeID IN (83) THEN DateDue END as HSTranscript,
CASE WHEN cmDocTypeID IN (126) THEN DateDue END as AcceptLetter,
CASE WHEN cmDocTypeID IN (150) THEN DateDue END as FAFSA,
CASE WHEN cmDocTypeID IN (155) THEN DateDue END as Fin AidApp,
S.FirstName,
S.LastName
FROM syStudent S (NOLOCK)
INNER JOIN
(SELECT DISTINCT
S.syStudentID
FROM syStudent S (NOLOCK)
JOIN cmActivity_vw A (NOLOCK)
ON A.syStudentID = S.syStudentID
AND A.cmTemplateID IN (16,195,283,290,291) --Application received
WHERE S.StartDate BETWEEN '5/1/07' AND '9/1/07' -- Expected Start Date
AND S.amPrevEducID = 1 --High School Grad
AND S.syCampusID = 5 --Main Campus
) TMP
on S.syStudentID = TMP.syStudentID
INNER JOIN cmDocument D (NOLOCK)
ON
D.syStudentID = S.syStudentID

Dan

|||

Dan:

One reason to use a stored procedure instead of a function is to encapsulate security -- specifically to dis-allow ad hoc ability to table yet still provide needed functionality. We have a number of clients that have in their standards that (1) rank-and-file users must not have any access to table components of databases and (2) all database data access be given by another means -- such as stored procedures or functions. There are also other reasons.

|||

Waldrop,

I certainly agree that if the user cannot use a Query that includes a sub-Query, because it violates some security regulation, then the solution I proposed is unsatisfactory.

I could not tell from the preceding posts that such security issues were involved, so I suggested what seems to me to be the simplest solution to obtain the desired dataset.

Dan

|||

Ok, I have created the following function:

CREATE FUNCTION dbo.fn_amEnrollmentTrackingDetailGet_cst (@.syStudentID INTEGER)
RETURNS @.amTrackingDetail TABLE (
syStudentID INTEGER,
SATACT DATETIME,
HSTranscript DATETIME,
AcceptLetter DATETIME,
FAFSA DATETIME,
FinAidApp DATETIME)
AS

BEGIN
DECLARE
@.SATACT DATETIME,
@.HSTranscript DATETIME,
@.AcceptLetter DATETIME,
@.FAFSA DATETIME,
@.FinAidApp DATETIME

SELECT
@.SATACT = CASE WHEN cmDocTypeID IN (81,110) THEN DateDue END,
@.HSTranscript = CASE WHEN cmDocTypeID IN (83) THEN DateDue END,
@.AcceptLetter = CASE WHEN cmDocTypeID IN (126) THEN DateDue END,
@.FAFSA = CASE WHEN cmDocTypeID IN (150) THEN DateDue END,
@.FinAidApp = CASE WHEN cmDocTypeID IN (155) THEN DateDue END
FROM
cmDocument (NOLOCK)
WHERE
syStudentID = @.syStudentID
ORDER BY
cmDocTypeID, DateDue

INSERT INTO @.amTrackingDetail
SELECT
S.syStudentID,
@.SATACT AS SATACT,
@.HSTranscript AS HSTranscript,
@.AcceptLetter AS AcceptLetter,
@.FAFSA AS FAFSA,
@.FinAidApp AS FinAidApp
FROM
syStudent S (NOLOCK)

WHERE S.syStudentID = @.syStudentID
RETURN
END

But when I try to reference that function in a SELECT statement like:

SELECT
dbo.fn_amEnrollmentTrackingDetailGet_cst(SyStudentID)
FROM
syStudent

I get: Invalid object name 'dbo.fn_amEnrollmentTrackingDetailGet_cst'.

|||

Charles:

You have defined a "Table valued function" and in your select statement you are referencing it like a "scalar function." Look at the CREATE FUNCTION article in books online to see the difference.

|||

This is an example using a table function from the 2005 AdventrueWorks database.

SELECT C.*

FROM HumanResources.Employee AS E

CROSS APPLY dbo.ufnGetContactInformation(EmployeeID)AS C

|||

Dan,

Thank you very much for your post. It was very helpful, especially here at the beginning of this project when we are verifying the dataset for accuracy. However, another reason that I am attracted to the function paradigm is that it seems that it would allow me to easily reference that function in other solutions.

|||

Charles:

Try altering your function call to something like:

select tf.syStudentID,
tf.SATACT,
tf.HSTranscript,
tf.AcceptLetter,
tf.FAFSA,
tf.FinAidApp
from syStudent a
cross apply fn_amEnrollmentTrackingDetailGet_cst(SyStudentID) tf

|||

I also saw another example of this at http://msdn2.microsoft.com/en-us/library/ms186755.aspx, but when I try the following code with a declared table, I get 'Line 22: Incorrect syntax near 'APPLY'.

DECLARE @.TableApplied TABLE (
syStudentID INTEGER)

INSERT @.TableApplied
SELECT DISTINCT
S.syStudentID
FROM
syStudent S (NOLOCK)
JOIN cmActivity_vw A (NOLOCK)
ON A.syStudentID = S.syStudentID
AND A.cmTemplateID IN (16,195,283,290,291) --Application received
-- and A.eventstatus = 'Closed'
WHERE
S.StartDate BETWEEN '8/1/07' AND '9/1/07' -- Expected Start Date
AND S.amPrevEducID = 1 --High School Grad
AND S.syCampusID = 5 --Main Campus

SELECT
C.*
FROM
@.TableApplied AS A
CROSS APPLY dbo.fn_amEnrollmentTrackingDetailGet_cst(A.SyStudentID) AS C

|||I noticed that the database compatibility level has to be 90 in order for CROSS APPLY to work. Ours is set to 80 and 90 is not an option in the drop down. :(|||If you are in 80 compatibility and cannot use CROSS APPLY, consider something like modifying your function to accept a NULL studentID as an argument; when a null student id is sent to the UDF return all of the rows from the table instead of rows for the specific student. Then you can INNER JOIN this to your syStudent table based on StudentID?

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

Callind Stored Proc from Stored Proc

I am trying to call a stored proc from within a stored proc as below, but it
throws a syntax error.
SELECT COUNT(*) FROM (EXEC spName)
I have no access to "spName" to make any amends, currnetly it returns a
large recordset of customers.
Anyone any ideas how to do this?Billy
INSERT INTO #tmp EXEC spName --Make sure that number of columns in the
#tmp should be match to the output from the SP
SELECT COUNT(*) FROM #tmp
"Billy" <Billy@.discussions.microsoft.com> wrote in message
news:26DC8B64-FF85-4BE0-8913-B84A021C2D40@.microsoft.com...
>I am trying to call a stored proc from within a stored proc as below, but
>it
> throws a syntax error.
> SELECT COUNT(*) FROM (EXEC spName)
> I have no access to "spName" to make any amends, currnetly it returns a
> large recordset of customers.
> Anyone any ideas how to do this?
>|||Try using "select @.@.rowcount" immediately after executing the proc.
Cheers,
Paul Ibison SQL Server MVP, www.replicationanswers.com .

Callind Stored Proc from Stored Proc

I am trying to call a stored proc from within a stored proc as below, but it
throws a syntax error.
SELECT COUNT(*) FROM (EXEC spName)
I have no access to "spName" to make any amends, currnetly it returns a
large recordset of customers.
Anyone any ideas how to do this?
Billy
INSERT INTO #tmp EXEC spName --Make sure that number of columns in the
#tmp should be match to the output from the SP
SELECT COUNT(*) FROM #tmp
"Billy" <Billy@.discussions.microsoft.com> wrote in message
news:26DC8B64-FF85-4BE0-8913-B84A021C2D40@.microsoft.com...
>I am trying to call a stored proc from within a stored proc as below, but
>it
> throws a syntax error.
> SELECT COUNT(*) FROM (EXEC spName)
> I have no access to "spName" to make any amends, currnetly it returns a
> large recordset of customers.
> Anyone any ideas how to do this?
>
|||Try using "select @.@.rowcount" immediately after executing the proc.
Cheers,
Paul Ibison SQL Server MVP, www.replicationanswers.com .

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