我想创建一个表值函数。这个函数有3个参数。每个返回的表列都将由SELECT语句填充。每个SELECT语句将在其WHERE子句中使用其中一个函数参数。
这是功能:
CREATE FUNCTION getChangeTypes(@add_name varchar(20),@change_name varchar(20), @remove_name varchar(20))
RETURNS @changeTypes TABLE (
addd varchar(20),
change varchar(20),
remove varchar(20)
)
AS
BEGIN
UPDATE @changeTypes
SET addd = CAST ((SELECT change_type_id FROM db_comp_change_types WHERE change_type_name = ''+@add_name+'') AS varchar(20))
UPDATE @changeTypes
SET change = CAST ((SELECT change_type_id FROM db_comp_change_types WHERE change_type_name = ''+@change_name+'') AS varchar(20))
UPDATE @changeTypes
SET remove = CAST ((SELECT change_type_id FROM db_comp_change_types WHERE change_type_name = ''+@remove_name+'') AS varchar(20))
RETURN;
END;
GO
这是对函数的调用:
select * from getChangeTypes('Added Column Size','Changed Column Size','Removed Column Size')
我意识到由于我使用函数参数的方式,WHERE无法正常工作。有人建议我可以正确地将函数参数合并到WHERE子句中吗?
非常感谢。
答案 0 :(得分:0)
您不得更新@changeTypes
,但必须插入
可能是这样的:
CREATE FUNCTION getChangeTypes(@add_name varchar(20),@change_name varchar(20), @remove_name varchar(20))
RETURNS @changeTypes TABLE (
addd varchar(20),
change varchar(20),
remove varchar(20)
)
AS
BEGIN
insert into @changeTypes(addd,change,remove) values(null,null,null)
UPDATE @changeTypes
SET addd = CAST ((SELECT change_type_id FROM db_comp_change_types WHERE change_type_name = ''+@add_name+'') AS varchar(20))
UPDATE @changeTypes
SET change = CAST ((SELECT change_type_id FROM db_comp_change_types WHERE change_type_name = ''+@change_name+'') AS varchar(20))
UPDATE @changeTypes
SET remove = CAST ((SELECT change_type_id FROM db_comp_change_types WHERE change_type_name = ''+@remove_name+'') AS varchar(20))
RETURN;
END;
GO
答案 1 :(得分:0)
如果子查询中有多个值,则会抛出错误
CREATE FUNCTION getChangeTypes(@add_name varchar(20),@change_name varchar(20), @remove_name varchar(20))
RETURNS @changeTypes TABLE (
addd varchar(20),
change varchar(20),
remove varchar(20)
)
AS
BEGIN
declare @db_comp_change_types Table (change_type_id int, change_type_name varchar(100))
Insert Into @db_comp_change_types
Select 1, 'Add' UNION
Select 2, 'Add' UNION
Select 3, 'Remove' UNION
Select 4, 'Change'
insert into @changeTypes
(addd,change,remove)
values(null,null,null)
UPDATE @changeTypes
SET addd = CAST ((SELECT TOP 1 change_type_id FROM @db_comp_change_types WHERE change_type_name = @add_name) AS varchar(20))
UPDATE @changeTypes
SET change = CAST ((SELECT TOP 1 change_type_id FROM @db_comp_change_types WHERE change_type_name = @change_name) AS varchar(20))
UPDATE @changeTypes
SET remove = CAST ((SELECT TOP 1 change_type_id FROM @db_comp_change_types WHERE change_type_name = @remove_name) AS varchar(20))
RETURN;
END
GO
我刚用Table变量替换了表。希望这会有所帮助。