Wednesday, March 28, 2012

Query help

Hello Everyone,

I have a query that looks something like this:

DEFINE @.VAR_A VARCHAR(6)

DECLARE trsite_cursor CURSOR FOR
SELECT DISTINCT AppField
FROM TABLE_1
ORDER BY 1

OPEN trsite_cursor

FETCH NEXT FROM trsite_cursor INTO @.VAR_A

WHILE @.@.FETCH_STATUS = 0
BEGIN
SET @.SELCMD ='SELECT * FROM TABLE_2
WHERE Field1 =' + @.VAR_A +
' ORDER BY 1,2,3;'
END
...
...
...
EXEC xp_sendmail @.query = @.SELCMD,
...
...

and the rest of the query.....

The column "AppField" in TABLE_1 has been defined as varchar. Let's
assume it contains the value: ABCD. When I run it, the query fails at
the SET @.SELCMD statement, saying that the column name ABCD is
invalid. It assumes that ABCD is a column name & not a value. However,
if AppField contains a numeric value, ex: 123, I don't get any errors
& the query outputs the desired results.

So, I guess, the question is: how do I make the SET @.SELCMD treat the
value in AppField as "ABCD" or 'ABCD' and not just ABCD?

Thanks,
Suhassurround the variable in quotes in the string

SET @.SELCMD ='SELECT * FROM TABLE_2
WHERE Field1 = '' ' + @.VAR_A +
'' ' ORDER BY 1,2,3;'

also you need another fetch before the END in the while loop or you
loop infinitly|||"Suhas" <sgtembe@.hotmail.com> wrote in message
news:5c440ee2.0311201306.4e7f5323@.posting.google.c om...
> SET @.SELCMD ='SELECT * FROM TABLE_2
> WHERE Field1 =' + @.VAR_A +
> ' ORDER BY 1,2,3;'
> assume it contains the value: ABCD. When I run it, the query fails at
> the SET @.SELCMD statement, saying that the column name ABCD is
> invalid. It assumes that ABCD is a column name & not a value. However,

--BEGIN PGP SIGNED MESSAGE--
Hash: SHA1

You need to enclose the value contained in @.VAR_A in single quotes when you
build the @.SELCMD string. In other words, you need to create a string that
contains single quotes. To do that, you use a *pair* of single quotes. So,
the SET command should look like this:

SET @.SELCMD ='SELECT * FROM TABLE_2
WHERE Field1 = ''' + @.VAR_A +
''' ORDER BY 1,2,3;'
END

If @.VAR_A = ABCD then this set command sets @.SELCMD to:
SELECT * FROM TABLE_2 WHERE Field1 = 'ABCD' ORDER BY 1,2,3;

--BEGIN PGP SIGNATURE--
Version: GnuPG v1.0.6 (MingW32)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj+9Pw0ACgkQFt8ABY6ZYSJ0bQCdE0eEaDLP8l 0QhwQVjnMe6DME
BY8Anjp68HxMiMxCqs9zLHWEHgTkQtGw
=agcy
--END PGP SIGNATURE--

No comments:

Post a Comment