1

I am using sql-server 2012:

drop table ttt
create table ttt(id int,amt int)
insert into ttt values(1,100),(2,200),(1,200),(3,400),(1,500)

create function dbo.t1(@id int)
returns int
with returns null on null input
as
begin
declare @amt_total int
select @amt_total=sum(amt) from ttt
where id=@id
return @amt_total
end

select t.id,t.amt,f.id from ttt t cross apply dbo.t1(t.id) f

The code returns following error on execution: Msg 208, Level 16, State 3, Line 16 Invalid object name 'dbo.t1'.

any help?

the function,tables are all present in same schema

2 Answers 2

5

The syntax you are using is suitable for table-valued user-defined functions which return a table data type instead of just a scalar value.

Try this syntax instead:

SELECT t.id, t.amt, f.id 
FROM ttt t 
CROSS APPLY (SELECT dbo.t1(t.id) ) f(id)
Sign up to request clarification or add additional context in comments.

4 Comments

I doing this select t.id as id1,t.amt as amt1,f.id as id2 from ttt t cross apply (select dbo.t1(t.id)) f but it gives error: Msg 8155, Level 16, State 2, Line 16 No column name was specified for column 1 of 'f'. Msg 207, Level 16, State 1, Line 16 Invalid column name 'id'.
@HareRamaHareKrishna Take a more careful look at my post: I am using f(id), not just f.
@GiorgosBetsos - Nice answer, I am still doubtful on why the OP wants to use CROSS APPLY
@ughai I think he took up the syntax used for inline UDFs, e.g. from a site like this sql-server-helper.com/tips/…
2

its a scalar function. you need to call it like this

select t.id,t.amt,dbo.t1(t.id) id from ttt t 

For more info about types of functions in SQL Server, refer here

1 Comment

It's correct, just change f alias to id to match exactly the OP expression.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.