Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

SQL Insert Trigger; variable scope issue

I'm trying to update another database while a record is appended in a table.
However, in the append trigger, I confront with a scope issue for a variable
(@lng_clientid_new)

If the variable @lng_clientid_new is not declared in the first line, an error appears (variable not declared).

However, if I do declare it in the first line, the variable @lng_clientid_new still contains null because the second declaration/variable assignment is not in the scope for the insert command.

So, is there any way I can use the @lng_clientid_new from the first select statement(line (2)) in the second insert statement (line (3))?

******************************************************
(1) DECLARE @lng_clientid_new bigint

(2) EXECUTE ('

USE ' + @targetdatabase + '

DECLARE @lng_clientid_new bigint
SET @lng_clientid_new = (SELECT lng_id FROM web_tbl_ge_clients where lng_mims_id=' + @lng_clientid + ')

(3) INSERT INTO
dbo.web_tbl_ge_users
(lng_clientid,str_first)
VALUES(' + @lng_clientid_new + ',' + "'"+ @str_first +"'" +')
')
******************************************************
[1251 byte] By [rkbnair] at [2007-11-11 8:47:50]
# 1 Re: SQL Insert Trigger; variable scope issue
So, is there any way I can use the @lng_clientid_new from the first select statement(line (2)) in the second insert statement (line (3))?

Absolutely. You just have a case of quotitis:)
EXECUTE ('

USE ' + @targetdatabase + '

DECLARE @lng_clientid_new bigint
SET @lng_clientid_new = (SELECT lng_id FROM web_tbl_ge_clients where lng_mims_id=' + @lng_clientid + ')

INSERT INTO
dbo.web_tbl_ge_users
(lng_clientid,str_first)
VALUES(@lng_clientid_new,' + "'"+ @str_first +"'" +')
')

@lng_clientid_new exists solely in the scope of your generated code, so the initial declaration outside of the generated code is redundant.

Rune
Rune Bivrin at 2007-11-11 23:46:55 >