【问题标题】:How do I create a function to accept [[customerID]] and return CustName Please look at details如何创建一个函数来接受 [[customerID]] 并返回 CustName 请查看详细信息
【发布时间】:2016-04-26 17:04:46
【问题描述】:

我被要求创建一个函数来接受 CustomerID 并为 CustomerID 返回 CustomerName,我是新的学生/开发人员如果问题不清楚,请告诉我,以便我可以添加更多详细信息,但这就是我被问到了。

【问题讨论】:

  • 我猜你应该从复习你的 SQL 学习材料开始。查看数据库架构也是一个很好的步骤。
  • 谢谢大卫。我主要使用我的学习材料和 Microsoft 网络,但有时我无法获得我想要的东西,所以我在这里停下来寻求像你这样的优秀开发人员的帮助和指导:)

标签: sql sql-server-2008 tsql


【解决方案1】:

SQL 中的functions 分为三种类型。忽略其他 CLR 函数...

create table test
(
id int,
name varchar(4)
)

insert into test
select 1,'abc'
union all
select 2,'cde'

1.标量函数取一个值,返回一个值

现在对于上表,您可以创建如下所示的标量函数

create function dbo.test
(
@id int
)
returns varchar(4)
as
begin
declare @name varchar(4)
select @name=name from test where id =@id
 return @name
End

你可以像这样调用它:

select  dbo.test(1)

2.内联表值函数:像标量函数一样接受单个输入并返回表

create function dbo.test
(
@id int
)
as 
returns TABLE
(
select * from test where id=@id)

你可以像这样调用它:

从 dbo.test(1) 中选择 *

3.多表值函数

create function dbo.test
(
@id int
)
returns 
@test table
(
id int,
name varchar(4)
)
as
begin

insert into @test
select * from test where id =@id

return

end

您可以像这样调用它: 从 dbo.test(1) 中选择 *

阅读任何一本 Itzik Ben Gan 的书籍,开始以应有的方式学习 SQL

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-16
    • 2014-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多