473,899 Members | 4,321 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem with Setting a variable in SQL String

Hi,

I am having problems setting the value of a variable in a SQL String
that I have to create dynamically in my procedure. The code that I
currently have is as follows:
set @sqlStatement=' Set @compare_string =' + '(Select ' +
@group_column_l ist_mod + ' from ' + @Tbl_Name + '_Sorted' + ' where
Identity_Column =' + ltrim(rtrim(str (@loop_counter) )) + ')'

exec(@sqlStatem ent)

The error message that I get is as follows:

Must declare the variable '@compare_strin g'.

Here @compare_string has already been declared in the procedure and I
don't have a problem using the variable anywhere else but this SQL
Statement (when called using the EXEC function).

I am not sure why SQL Server can't see the variable declared when used
in a string in conjunction with EXEC. Is this a syntax issue? Any help
on this issue would be greatly appreciated!

Thanks in advance.
Jul 20 '05 #1
5 13380
You need a parms string and an exec string, like this:

SET @Parms = `@compare_strin g`

set @sqlStatement=' Set @compare_string =' + '(Select ' +
@group_column_l ist_mod + ' from ' + @Tbl_Name + '_Sorted' + ' where
Identity_Column =' + ltrim(rtrim(str (@loop_counter) )) + ')'

EXECUTE sp_executesql @sqlStatement, @Parms, @compare_string

SET @Error = COALESCE ( NULLIF ( @Error, 0 ), @@ERROR )

exec(@sqlStatem ent)

The error message that I get is as follows:

Must declare the variable '@compare_strin g'.

Here @compare_string has already been declared in the procedure and I
don't have a problem using the variable anywhere else but this SQL
Statement (when called using the EXEC function).

I am not sure why SQL Server can't see the variable declared when used
in a string in conjunction with EXEC. Is this a syntax issue? Any help
on this issue would be greatly appreciated!

Thanks in advance.

Jul 20 '05 #2
Thanks for your reply. The sp_executesql procedure still doesn't give
the desired results. I am posting the updated piece of code and sample
output from the Query Analyzer.
------------------
set @parameter_Stri ng=N'@compare_s tring nvarchar(4000)'

set @sqlStatement=' Set @compare_string =(Select ' +
@group_column_l ist_mod + ' from ' + @Tbl_Name + '_Sorted' + ' where
Identity_Column =' + ltrim(rtrim(str (@loop_counter) )) + ')'

Print @sqlStatement
EXECUTE sp_executesql @sqlStatement,@ parameter_Strin g,@compare_stri ng

Print @compare_String
------------------

When I print the value of @compare_String in the end its a NULL.
However, if I run the same query without the set @compare_string
clause, it does work perfectly and returns the values of two columns
concatenated together. Any clues as to where I might be going wrong?

Thanks,
"Robin Tucker" <id************ *************@r eallyidont.com> wrote in message news:<bs******* ************@ne ws.demon.co.uk> ...
You need a parms string and an exec string, like this:

SET @Parms = `@compare_strin g`

set @sqlStatement=' Set @compare_string =' + '(Select ' +
@group_column_l ist_mod + ' from ' + @Tbl_Name + '_Sorted' + ' where
Identity_Column =' + ltrim(rtrim(str (@loop_counter) )) + ')'

EXECUTE sp_executesql @sqlStatement, @Parms, @compare_string

SET @Error = COALESCE ( NULLIF ( @Error, 0 ), @@ERROR )

exec(@sqlStatem ent)

The error message that I get is as follows:

Must declare the variable '@compare_strin g'.

Here @compare_string has already been declared in the procedure and I
don't have a problem using the variable anywhere else but this SQL
Statement (when called using the EXEC function).

I am not sure why SQL Server can't see the variable declared when used
in a string in conjunction with EXEC. Is this a syntax issue? Any help
on this issue would be greatly appreciated!

Thanks in advance.

Jul 20 '05 #3
[posted and mailed, please reply in news]

Aamer Nazir (aa***********@ hotmail.com) writes:
I am having problems setting the value of a variable in a SQL String
that I have to create dynamically in my procedure. The code that I
currently have is as follows:
set @sqlStatement=' Set @compare_string =' + '(Select ' +
@group_column_l ist_mod + ' from ' + @Tbl_Name + '_Sorted' + ' where
Identity_Column =' + ltrim(rtrim(str (@loop_counter) )) + ')'

exec(@sqlStatem ent)

The error message that I get is as follows:

Must declare the variable '@compare_strin g'.

Here @compare_string has already been declared in the procedure and I
don't have a problem using the variable anywhere else but this SQL
Statement (when called using the EXEC function).


The EXEC() statement is another scope which is not part of your procedure.
Thus, @compare_string is not defined in that example.

For better examples than the one posted, see
http://support.microsoft.com/?id=262499 and
http://www.sommarskog.se/dynamic_sql.html#sp_executesql.
--
Erland Sommarskog, SQL Server MVP, so****@algonet. se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 20 '05 #4
Yes, that won't work. Sorry, I just focused on the parameter part.

You can just do this:

select @compare_string = mytable.myfield FROM mytable where Identity_Column
= myvalue

or, in your specific case:

'Select @compare_string =' + @group_column_l ist_mod + ' from ' + @Tbl_Name +
'_Sorted' + ' where Identity_Column =' + ltrim(rtrim(str @loop_counter)) '

At least this is the syntax you should use in this case. Otherwise, you are
effectively trying to bind @compare_string to a recordset result, which
doesn't work.

Make sure you add in the error checking afterwards!! :)

"Aamer Nazir" <aa***********@ hotmail.com> wrote in message
news:60******** *************** ***@posting.goo gle.com...
Thanks for your reply. The sp_executesql procedure still doesn't give
the desired results. I am posting the updated piece of code and sample
output from the Query Analyzer.
------------------
set @parameter_Stri ng=N'@compare_s tring nvarchar(4000)'

set @sqlStatement=' Set @compare_string =(Select ' +
@group_column_l ist_mod + ' from ' + @Tbl_Name + '_Sorted' + ' where
Identity_Column =' + ltrim(rtrim(str (@loop_counter) )) + ')'

Print @sqlStatement
EXECUTE sp_executesql @sqlStatement,@ parameter_Strin g,@compare_stri ng

Print @compare_String
------------------

When I print the value of @compare_String in the end its a NULL.
However, if I run the same query without the set @compare_string
clause, it does work perfectly and returns the values of two columns
concatenated together. Any clues as to where I might be going wrong?

Thanks,
"Robin Tucker" <id************ *************@r eallyidont.com> wrote in

message news:<bs******* ************@ne ws.demon.co.uk> ...
You need a parms string and an exec string, like this:

SET @Parms = `@compare_strin g`

set @sqlStatement=' Set @compare_string =' + '(Select ' +
@group_column_l ist_mod + ' from ' + @Tbl_Name + '_Sorted' + ' where
Identity_Column =' + ltrim(rtrim(str (@loop_counter) )) + ')'

EXECUTE sp_executesql @sqlStatement, @Parms, @compare_string

SET @Error = COALESCE ( NULLIF ( @Error, 0 ), @@ERROR )

exec(@sqlStatem ent)

The error message that I get is as follows:

Must declare the variable '@compare_strin g'.

Here @compare_string has already been declared in the procedure and I
don't have a problem using the variable anywhere else but this SQL
Statement (when called using the EXEC function).

I am not sure why SQL Server can't see the variable declared when used
in a string in conjunction with EXEC. Is this a syntax issue? Any help
on this issue would be greatly appreciated!

Thanks in advance.

Jul 20 '05 #5
Thanks for pointing me to the right direction. The code works
perfectly fine now. The problem was with the syntax that Erland
Sommarskog mentioned in his posting. You have to specify the parameter
type (input or output) in the parameter specification string (the
second argument to sp_executesql).

Best Regards,
"Robin Tucker" <id************ *************@r eallyidont.com> wrote in message news:<bs******* ************@ne ws.demon.co.uk> ...
Yes, that won't work. Sorry, I just focused on the parameter part.

You can just do this:

select @compare_string = mytable.myfield FROM mytable where Identity_Column
= myvalue

or, in your specific case:

'Select @compare_string =' + @group_column_l ist_mod + ' from ' + @Tbl_Name +
'_Sorted' + ' where Identity_Column =' + ltrim(rtrim(str @loop_counter)) '

At least this is the syntax you should use in this case. Otherwise, you are
effectively trying to bind @compare_string to a recordset result, which
doesn't work.

Make sure you add in the error checking afterwards!! :)

"Aamer Nazir" <aa***********@ hotmail.com> wrote in message
news:60******** *************** ***@posting.goo gle.com...
Thanks for your reply. The sp_executesql procedure still doesn't give
the desired results. I am posting the updated piece of code and sample
output from the Query Analyzer.
------------------
set @parameter_Stri ng=N'@compare_s tring nvarchar(4000)'

set @sqlStatement=' Set @compare_string =(Select ' +
@group_column_l ist_mod + ' from ' + @Tbl_Name + '_Sorted' + ' where
Identity_Column =' + ltrim(rtrim(str (@loop_counter) )) + ')'

Print @sqlStatement
EXECUTE sp_executesql @sqlStatement,@ parameter_Strin g,@compare_stri ng

Print @compare_String
------------------

When I print the value of @compare_String in the end its a NULL.
However, if I run the same query without the set @compare_string
clause, it does work perfectly and returns the values of two columns
concatenated together. Any clues as to where I might be going wrong?

Thanks,
"Robin Tucker" <id************ *************@r eallyidont.com> wrote in

message news:<bs******* ************@ne ws.demon.co.uk> ...
You need a parms string and an exec string, like this:

SET @Parms = `@compare_strin g`

set @sqlStatement=' Set @compare_string =' + '(Select ' +
@group_column_l ist_mod + ' from ' + @Tbl_Name + '_Sorted' + ' where
Identity_Column =' + ltrim(rtrim(str (@loop_counter) )) + ')'

EXECUTE sp_executesql @sqlStatement, @Parms, @compare_string

SET @Error = COALESCE ( NULLIF ( @Error, 0 ), @@ERROR )

>
> exec(@sqlStatem ent)
>
> The error message that I get is as follows:
>
> Must declare the variable '@compare_strin g'.
>
> Here @compare_string has already been declared in the procedure and I
> don't have a problem using the variable anywhere else but this SQL
> Statement (when called using the EXEC function).
>
> I am not sure why SQL Server can't see the variable declared when used
> in a string in conjunction with EXEC. Is this a syntax issue? Any help
> on this issue would be greatly appreciated!
>
> Thanks in advance.

Jul 20 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
3060
by: | last post by:
Hi, I'm trying to use the cookie munging session handling behaviour of asp.net instead of cookies themselves as I'm finding quite a few people are barring cookies (especially AOL users). If I change the setting in web.config everything seems to work fine as long as I'm using relative paths. The problem is I've got a menuing system that's generated from a site-wide template - so I use a fixed path from the application root - (ie:...
2
2933
by: R Duke | last post by:
I have tried everything I can think of to change the visible property of a design time created control from a dynamically created control's command event handler. Here is the scenario. I have a WebForm with some textboxes, dropdownlists, a panel, imagebutton and so on. When I click on the image button (which was created at design time) I dynamically build a table. In each of row of that new table I put several cells and one cell...
1
4766
by: Andrew | last post by:
Hey all, Working on revamping our Intranet here and making use of the LDPA, Active Directory, Directory Services, etc. that .Net provides. I am still fairly new on this subject, so the problem I have run into I am not sure how to fix, and really not sure what is causing it. Here's what is going on (test server - Windows 2003 Server): I have a page in a folder (under anonymous authentication in IIS6) that has a link on it that...
15
2425
by: Ron L | last post by:
We are working on a distributed VB.Net application which will access a SQL database located on a known server. Each client will run on the user's local machine. To implement this, we are trying to use remoting for our access to the SQL server, with the remoting being via IIS. Since all of our users will have accounts in the destination domain, we want to have IIS handle the security for us and not allow anonymous. We have set this up...
6
1533
by: David Hearn | last post by:
I have a property in a user control that I am setting: Private strPageName as String Public Property PageName() as String Get Return strPageName End Get Set(byVal Value as String) strPageName = Value End Set
3
1175
by: Toni | last post by:
Hello! I'm building an application where the user can update his own personal information in a database using a form. The program fetches the user's information from the database, fills the form with this information, then the user makes the changes that he wants, clicks the "Update" button and the updated information is sent back to the database. But I have a problem. My program is supposed to work like this: txtNamefield.text = "John...
8
2462
by: sara | last post by:
I have a report that runs fine with data. If there is no data, I have its NO Data event sending a MsgBox and cancelling the report. Then it seems I still get the 2501 message on the Open Report command, even though I have the code to trap Err 2501 (from many postings - all looked the same to me) on the button the user pressed to get the report. I never see the code going to my error handling on the button. If I debug, I am in an...
1
6529
by: laredotornado | last post by:
Hi, I'm using PHP 4.4.4 on Apache 2 on Fedora Core 5. PHP was installed using Apache's apxs and the php library was installed to /usr/local/php. However, when I set my "error_reporting" setting to be "E_ALL", notices are still not getting reported. The perms on my file are 664, with owner root and group root. The php.ini file is located at /usr/local/lib/php/php.ini. Any ideas why the setting does not seem to be having an effect? ...
5
1528
by: tshad | last post by:
In VS 2003, I am setting up an abstract class that is setting up classes for each datatype of VB.Net (as well as C#). I am trying to set it up so that most of the work is done in the Abstract Class. It seems to work pretty well. I have the actual data memory variables stored as an object as each class will use it as a different type of object (not sure if this is a problem). The system can tell if the variable is a string, boolean or...
0
9997
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
11276
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10976
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10497
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9671
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
7204
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
6082
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4301
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3320
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.