我在Teradata SQL中创建了一个宏(我第一次这样做)。过去,我已经将SAS用于宏,所以这就是我的背景。但是对于这个项目,我需要使用Teradata,而宏确实会有所帮助。
CREATE MACRO member_count(state CHAR(2)) AS
(
Select
':state1' as state,
other_vars, etc
FROM database.:state_member;
);
EXEC member_count(NM);
我想在这里发生的是,每当使用短语':state'时,都会在代码中调用字母NM。但是,当我运行代码时,出现错误3707:语法错误,应在'。'之间输入类似'UDFCALLNAME'的关键字。和':'。
我想完成的宏是否可能?如果是这样,我需要更改什么?
答案 0 :(得分:2)
因为您希望宏的调用者说出他们将从中选择哪个表,所以您必须切换到动态生成的SQL语句,这只能在过程中进行。
一个大概的轮廓/示例,看起来像什么:
CREATE PROCEDURE member_count(IN state CHAR(2))
--We have to tell it here that we will be returning a result set
DYNAMIC RESULT SETS 1
BEGIN
--Declare variables we will be using at the top
--One variable for the sql string
DECLARE my_sql VARCHAR(500);
--And another for the cursor that we will open for the result set
DECLARE my_cursor CURSOR WITH RETURN ONLY FOR my_statement;
--Now we build our dynamically generated sql statement
--we use two single quotes together to escape the quote character
--(essentially we want a single quote in the SQL statement so we must
--double it as it's already inside single quotes).
SET my_sql = 'Select
''' || state1 || ''' as state,
other_vars, etc
FROM database.' || state_member || ';';
--Now we "prepare" the "statement" from our string
PREPARE my_statement FROM my_sql;
--and we open the cursor. We don't close it because we want it returned.
OPEN my_cursor;
END
由于这里没有声明或填充:state_member
变量,因此需要吐口水才能工作,但这也不在您的宏尝试中,因此可能超出此问题的范围。 / p>