想要编写一个函数,我可以从表中的任意两列调用,以便在同一个表中获取结果列。 表:极致 列:CustomerID,LastName,FirstName,EmailAdress,MailingAddress,City,State,Zip
我可以从FirstName和姓氏中获取EmailAddress吗? 我可以从CustomerID和City获得Zip吗?
我目前为EmailAddress所做的事情:
CREATE FUNCTION fnEmailAddress
(@LastName varchar (255), @FirstName varchar (255))
RETURNS table
RETURN (SELECT EmailAddress
FROM Acme
WHERE FirstName = @FirstName AND LastName = @LastName);
END
所以以下内容会给我brenda.chen@gmail.com: EXEC fnEmailAddress('Brenda'+'陈')
但它不起作用:(
答案 0 :(得分:1)
如果我理解正确,你需要一个能够适应输入组合的几种可能性的函数,因为你准备输入的列可能在每个函数调用中都有所不同。如果是这样的话:
最后,选择以下其中一个:
NULL
,然后使用自动传递任何WHERE
输入的NULL
子句查询一次(示例:WHERE COL1 = ISNULL(@PAR1, COL1) AND COL2 = ISNULL(@PAR2, COL2)
,需要更多NULL
列列的逻辑),IF
/ ELSE
命令在几个不同的查询之间切换(不同的查询可能是维护问题,所以尽可能避免)。以下是基于我已有的内容的示例,尽管它使用IF
/ ELSE
方法。请尝试改为NULL
/ ISNULL
:
CREATE FUNCTION [dbo].[SomeWackoName]
(@FirstArm tinyint, @SecondArm tinyint, @FirstLeg tinyint, @SecondLeg tinyint)
RETURNS @Results TABLE(
[Value] varchar(60)
) AS
BEGIN
-- For input, we need both arms, or both legs. It is acceptable to provide three inputs.
-- It is unacceptable to provide all four inputs (confusing), or failing to provide any full pair (like one input, or two unpaired inputs).
DECLARE @Validator tinyint = CASE WHEN @FirstArm + @SecondArm IS NULL THEN 0 ELSE 1 END + CASE WHEN @FirstLeg + @SecondLeg IS NULL THEN 0 ELSE 2 END
IF @Validator NOT BETWEEN 1 AND 2 RETURN --THROW 50000, 'INCORRECT INPUT WHYYYYYYYYYYYYYYY WHYYYYYYYYYYYYYYYYYY', 0;
-- Depending on input provided, decide how to behave.
IF @Validator = 1
INSERT INTO @Results SELECT 'I GOT THE ARMS. POPULATE WITH LEGS!!'
ELSE IF @Validator = 2
INSERT INTO @Results SELECT 'I GOT THE LEGS. POPULATE WITH ARMS!!'
-- Return results.
RETURN
END
答案 1 :(得分:0)
CREATE FUNCTION fnEmailAddress
(
@LastName varchar (255)=null, @FirstName varchar (255)=null,
@streetNumber varchar(255)=null,@streetname varchar (255)=null
)
RETURNS table
Select case when @firstname+@lastname is not null then EMail Else LastName End Column3
from person
where
(
case when @firstname+@lastname is not null
then case when FirstName=@firstname and LastName=@lastname
then 1 else 0 End
when @StreetNumber+@streetname is not null
then case when StreetName=@Streetname and StreetNumber=@streetNumber
then 1 Else 0 End
End
)=1
该函数应该有4个输入参数,只传递前两个参数或最后两个参数。
select语句中的CASE将获得“Email”或“LastName”,具体取决于输入参数是否为null。
类似地,where语句中的CASE将根据输入参数null选择应该应用哪个过滤器,并且将基于此获取结果。