xcaliber2222
Programmer
Hello, I've used user defined functions but never to return a resultset (as you would a view) and then use that as part of a select statement.
Here is my select statement:
I need to replace the DIST_DEALER_XREF with a function that uses this query which returns the same result set:
I know I can create a function like so:
Then use it in my query like so:
But in this case I'm having trouble trying to figure out how to actually get the query with the join to return the values properly. I believe with what I'm trying to do I don't even need to pass parameters to the function because I'm filtering the results in the final select statement.
I've tried several approaches but I think my syntax is way off. If someone could please show me the correct way to do this or a better approach completely I would really appreciate it.
Thank you,
Alejandro
Here is my select statement:
Code:
SELECT count(*) AS numberOfClaims
FROM DIST_DEALER_XREF RIGHT JOIN Claim_Dist_Owner ON DIST_DEALER_XREF.DEALER_NUM = Claim_Dist_Owner.CD_DLR_NUM
Where (Claim_Dist_Owner.CD_DIST_NUM='12345') OR (DIST_DEALER_XREF.DIST_NUM='12345') OR (Claim_Dist_Owner.CD_DIST_NUM='AB123') OR
(DIST_DEALER_XREF.DIST_NUM='AB123')
I need to replace the DIST_DEALER_XREF with a function that uses this query which returns the same result set:
Code:
select
convert(nvarchar(8),U.user_name) as DEALER_NUM,
convert(nvarchar(6),d.value_string) as DIST_NUM,
ptd.Dealer_Name,
ptd.Contact_name,
ptd.Address,
ptd.City,
ptd.state as ST,
ptd.ZIP,
ptd.Country,
ptd.Phone,
ptd.Phone_Toll_Free,
ptd.Fax,
ptd.OEM_Service,
ptd.Full_Service,
ptd.website as Web_Site_URL,
ptd.Email,
ptd.show_on_dist_map as MAP_DISPLAY_FL
from
TEST2.PT.dbo.dynamic_data_tbl D,
TEST2.PT.dbo.users U,
TEST2.PT.dbo.PTDealer PTD
where
d.object_id = u.user_id
and u.user_name = ptd.company_id
I know I can create a function like so:
Code:
CREATE FUNCTION dbo.MyFunction
(
@Param1, ... several parameters ...
)
RETURNS TABLE
AS
RETURN
SELECT
[KEY_ID] = MyID
FROM dbo.MyTable
WHERE
(@Param1 IS NULL OR Col1 = @Param1)
AND ... several more ...
GO
Then use it in my query like so:
Code:
SELECT TOP 500 Col1, Col2, ...
FROM dbo.MyFunction(@Param1, ... )
JOIN dbo.MyTable
ON MyID = KEY_ID
But in this case I'm having trouble trying to figure out how to actually get the query with the join to return the values properly. I believe with what I'm trying to do I don't even need to pass parameters to the function because I'm filtering the results in the final select statement.
I've tried several approaches but I think my syntax is way off. If someone could please show me the correct way to do this or a better approach completely I would really appreciate it.
Thank you,
Alejandro