我是Sql函数的新手,想要一些关于为什么我的函数没有像我想的那样表现的指针..
我的数据库有一个UserLogin表,其中包含所有用户电子邮件等。 然后它有一个Customer,Teachers和Advisors表,这3个表中的任何一个ID都引用UserLogin表中的ID。这个结构值得商榷,但我已经解决了这个问题。
我的功能的目的是找到一个用户名,给出他的ID。
CREATE FUNCTION GetUserLoginName
(
-- Add the parameters
@id int
)
RETURNS varchar
AS
BEGIN
Declare @firstName varchar
declare @lastName varchar
-- If an advisor exists with ID, find names in Advisor table.
if (exists(
select *
from Advisor
where ID = @id))
Begin
SET @firstName = (
select u.FirstName
from dbo.Advisor as u
WHERE u.ID = @id)
SET @lastName = (
select u.LastName
from dbo.Advisor as u
WHERE u.ID = @id)
End
-- Else if a customer exists with ID, find names in customer table.
else if (exists(
select *
from Customer
where ID = @id))
Begin
SET @firstName = (
select u.FirstName
from dbo.Customer as u
WHERE u.ID = @id)
SET @lastName = (
select u.LastName
from dbo.Customer as u
WHERE u.ID = @id)
End
-- Else if a Teacher exists with ID, find names in Teacher table.
else if (exists(
select *
from Teacher
where ID = @id))
Begin
SET @firstName = (
select u.FirstName
from dbo.Teacher as u
WHERE u.ID = @id)
SET @lastName = (
select u.LastName
from dbo.Teacher as u
WHERE u.ID = @id)
End
RETURN (@firstName + ' ' + @lastName)
END
该功能正在返回名称为“Karl Pedersen”的“K”......
答案 0 :(得分:0)
除了定义varchars的大小之外,您还可以使此函数更简单。这些方面的东西。
C
REATE FUNCTION GetUserLoginName
(
-- Add the parameters
@id int
)
RETURNS varchar(30)
AS
BEGIN
Declare @FullName varchar(30)
select @FullName = x.FullName
from
(
select a.FirstName + ' ' + a.LastName as FullName
from dbo.Advisor as a
WHERE a.ID = @id
union all
select c.FirstName + ' ' + c.LastName
from dbo.Customer as c
WHERE c.ID = @id
union all
select t.FirstName + ' ' + t.LastName
from dbo.Teacher as t
WHERE t.ID = @id
) x
return @FullName
end