-1

我想创建一个表值函数。此函数将有 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 子句中的方法吗?

非常感谢。

4

2 回答 2

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
于 2013-10-09T13:50:48.457 回答
0

tf 子查询中有多个值,那么这会抛出错误

    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

我刚刚用表变量替换了表。希望这会有所帮助。

于 2014-10-27T14:35:44.490 回答