如何创建具有可变输入量的 SQL 函数?
How to create SQL functions with a variable amount of input?
我想创建一个函数,将指定列从任何 table 连接到我的主 table。我对该功能的预期用途如下:
Select *
From [Main Table] A
Outer Apply get_Factor([Table1], [Column_Name], Col1, [Key1] ) As [Factor_A]
Outer Apply get_Factor([Table2], [Column_Name], Col2, [Key2] ) As [Factor_B]
Outer Apply get_Factor([Table9], [Column_Name], Col1, [Key1], Col2, [Key2]) As [Factor_C]
该函数本质上是一个连接,但我现在无法弄清楚如何让它拥有动态数量的键。
CREATE FUNCTION [dbo].[get_Factor]
(
@Table_Name VARCHAR(10)
, @Column_Name VARCHAR(10)
/* not sure how to add a dynamic amount of keys here. There can be more than 3 keys. */
)
RETURNS TABLE
AS
RETURN
(
SELECT @Column_Name
FROM @Table_Name
WHERE @Col1 = @key1 And @Col2 = @key2 And @Col3 = @key3 /* ...etc */
)
GO
列应该是字符串(例如 'Company Code'),而键应该是主 table 中的变量(例如 [公司代码])。
您的代码无法运行。您不能用参数替换查询中的 identifiers,因此您不能按预期使用 @table_name
或 @column_name
。
显而易见的解决方案是使用动态 SQL。但是,SQL 服务器用户定义函数中不允许动态 SQL。
有一些神秘的选择可以解决这个问题,例如:
- 编写一个 CLR 函数,打开与 SQL 服务器的新连接。为此,这太复杂了。
- 使用存储过程,但不能在查询中使用该函数。
或者,找到其他方法来完成您想要的。您对此类功能的需求可能是由糟糕的数据模型驱动的,因此修复数据模型将简化您的查询。
我想创建一个函数,将指定列从任何 table 连接到我的主 table。我对该功能的预期用途如下:
Select *
From [Main Table] A
Outer Apply get_Factor([Table1], [Column_Name], Col1, [Key1] ) As [Factor_A]
Outer Apply get_Factor([Table2], [Column_Name], Col2, [Key2] ) As [Factor_B]
Outer Apply get_Factor([Table9], [Column_Name], Col1, [Key1], Col2, [Key2]) As [Factor_C]
该函数本质上是一个连接,但我现在无法弄清楚如何让它拥有动态数量的键。
CREATE FUNCTION [dbo].[get_Factor]
(
@Table_Name VARCHAR(10)
, @Column_Name VARCHAR(10)
/* not sure how to add a dynamic amount of keys here. There can be more than 3 keys. */
)
RETURNS TABLE
AS
RETURN
(
SELECT @Column_Name
FROM @Table_Name
WHERE @Col1 = @key1 And @Col2 = @key2 And @Col3 = @key3 /* ...etc */
)
GO
列应该是字符串(例如 'Company Code'),而键应该是主 table 中的变量(例如 [公司代码])。
您的代码无法运行。您不能用参数替换查询中的 identifiers,因此您不能按预期使用 @table_name
或 @column_name
。
显而易见的解决方案是使用动态 SQL。但是,SQL 服务器用户定义函数中不允许动态 SQL。
有一些神秘的选择可以解决这个问题,例如:
- 编写一个 CLR 函数,打开与 SQL 服务器的新连接。为此,这太复杂了。
- 使用存储过程,但不能在查询中使用该函数。
或者,找到其他方法来完成您想要的。您对此类功能的需求可能是由糟糕的数据模型驱动的,因此修复数据模型将简化您的查询。