如何在SQL语句中使用动态变量

时间:2012-08-07 18:45:31

标签: sql sql-server-2008 tsql db2

我正在创建一个upate触发器。我有一种情况,我需要测试表列上的条件,而不知道确切的列名是什么。触发器是通用的,可以应用于任何具有不同列的表。

的伪代码:

// define a cursor that loops through all columns in "MyTable"
Define cursor C1 for (select COLS from SYSCAT.TABLES where TABS="MyTable")
FOR
// take the next column from the cursor
@temp_var = C1.COLS
// DELETED and INSERTED are tables that also contain the same columns as "MyTable" table.
if(DELETED.@temp_var <> INSERTED.@temp_var)
THEN
...

上述陈述if(DELETED.@temp_var <> ...当然不起作用,但也许你可以看到我想要做什么?所以我希望它在运行时间,例如if(DELETED.MyColumn <>... where "MyColumn""MyTable"以及INSERTEDDELETED columns中的列。请注意,因为此方法应该是通用的,所以我事先不知道该表具有哪些列(取决于所使用的特定表)。

关于如何动态构建if语句的任何想法?

1 个答案:

答案 0 :(得分:0)

在DB2 SQL中,您无法动态引用列。因此,您将无法仅使用SQL执行此操作。您可以从触发器内调用另一种语言编写的外部过程。或者,您可以根据自己的目标重新考虑整体设计。我没有看到任何其他选择。