By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,700 Members | 1,579 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,700 IT Pros & Developers. It's quick & easy.

Query help

P: n/a
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,
Suhas
Jul 20 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
surround 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
Jul 20 '05 #2

P: n/a
"Suhas" <sg*****@hotmail.com> wrote in message
news:5c**************************@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-----

Jul 20 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.