Advertisement

02.21.2008 at 09:06AM PST, ID: 23181767
[x]
Attachment Details
[x]
The Solution Rating System

With so many solutions, how can you tell which solutions are most likely to help you and which ones are not? To provide you with a tool to use, we rate our solutions based on various elements that most accurately determine if a solution is a quality solution. To explain what factors affect the solution rating, here are the elements we take into consideration when formulating our solution rating.

  • The Grade of the Solution
  • The Zone Rank of the Expert Providing the Solution
  • The Number of Author and Expert Comments
  • The Number of Experts Contributing
  • The Feedback of the Community

Your Input Matters
Because of the way the system is set up, the most important variable in this equation is you. As a member of Experts Exchange, you are able to cast your vote on the quality of the solutions in regard to how complete, accurate, helpful and easy to understand each solution is. When you provide your feedback, each rating is adjusted accordingly. So, if you see a solution that has a poor rating that you think is a good solution, let us know by rating it. As you do, the rating will be adjusted and will become more accurate for other members of our site.

If you have any suggestions that you would like to make for our rating system, please ask a question in the Suggestions Zone of Community Support.

Thank you!

Putting Quote Around a Literal in T-SQL
Tags: T-SQL, n/a, n/a
GOAL
Need to set a variable (@LookupKeyFieldValue )  to a value looked up in database, where the lookup is accomplished like this:
select @LookupKeyFieldValue = [idContextHistoric] from [tlk_VAI_ContextHistoric] where [txtContextHistoric] = 'Agriculture'

PROBLEM
Getting the quotation marks around Agriculture is proving quite the puzzler.  Is it just me, or is T-SQL a pain, due to the fact it uses only single quotation marks that do not nest well?  I think T-SQL needs some reengineering.

ANYWAY
Here is my code to make the select:
DECLARE @AccessFieldName varchar(1000)
DECLARE @FieldValueFromName varchar(1000)
DECLARE @FieldValueFromNamez varchar(1000)
DECLARE @XTableName varchar(1000)
DECLARE @LookupTable varchar(1000)
DECLARE @LookupKeyFieldName varchar(1000)
DECLARE @LookupKeyFieldValue      int
DECLARE @LookupFieldName varchar(1000)

SET @AccessFieldName = 'IsHistoricContextAgriculture'
SET @FieldValueFromName ='Agriculture'
SET @XTableName = 'tbl_VAI_SiteXContextHistoric'
SET @LookupTable = 'tlk_VAI_ContextHistoric'
SET @LookupKeyFieldName = 'idContextHistoric'
SET @LookupFieldName  = 'txtContextHistoric'

DECLARE @sql nvarchar(2000)
set @sql = 'select @LookupKeyFieldValue = [' + @LookupKeyFieldName + '] from [' + @LookupTable + '] where [' + @LookupFieldName + '] = ' + @FieldValueFromName + ' '
print (@sql)

The result of print(@sql) is missing the quotes around Agriculture, like this:
select @LookupKeyFieldValue = [idContextHistoric] from [tlk_VAI_ContextHistoric] where [txtContextHistoric] = Agriculture  

This bombs, due to no quotation marks around Agriculture.

I have systematically gone through a variety of ways of getting quotes around Agriculture.  The only example I got to work required setting the value of @FieldValueFromName ='''Agriculture'''.   I really don't want to put '' before and after every string in my database, so I really need to find a way to insert quotation marks into this dynamic T-SQL.

ANOTHER WAY OF PUTTING SAME QUESTION:
Select '' returns an empty string.
How do you SELECT a single quote?
select ''' returns an error.

There has to be a way to select a single quote mark, then concatenate the quote mark to another string, making a literal appear in quotes within a dynamic sql statement.

In any event, what I need is a way to generate the sql shown above, with the quotation marks around the value of @FieldValueFromName
Start your free trial to view this solution
Question Stats
Zone: Microsoft
Question Asked By: Danimal
Solution Provided By: fesnyng
Participating Experts: 4
Solution Grade: A
Views: 288
Translate:
Loading Advertisement...
02.21.2008 at 09:07AM PST, ID: 20949648

Rank: Genius

All comments and solutions are available to Premium Service Members only.

Start your 7 day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
02.21.2008 at 09:25AM PST, ID: 20949848

All comments and solutions are available to Premium Service Members only.

Start your 7 day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
02.21.2008 at 09:33AM PST, ID: 20949910

Rank: Genius

All comments and solutions are available to Premium Service Members only.

Start your 7 day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
02.21.2008 at 09:52AM PST, ID: 20950065

All comments and solutions are available to Premium Service Members only.

Start your 7 day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
02.21.2008 at 10:18AM PST, ID: 20950317

All comments and solutions are available to Premium Service Members only.

Start your 7 day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
02.21.2008 at 11:02AM PST, ID: 20950729

Rank: Genius

All comments and solutions are available to Premium Service Members only.

Start your 7 day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
02.21.2008 at 12:12PM PST, ID: 20951401

All comments and solutions are available to Premium Service Members only.

Start your 7 day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
02.21.2008 at 01:36PM PST, ID: 20952100

Rank: Genius

All comments and solutions are available to Premium Service Members only.

Start your 7 day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
02.21.2008 at 03:04PM PST, ID: 20952844

All comments and solutions are available to Premium Service Members only.

Start your 7 day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
02.21.2008 at 03:14PM PST, ID: 20952898

All comments and solutions are available to Premium Service Members only.

Start your 7 day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
02.21.2008 at 03:27PM PST, ID: 20953012

All comments and solutions are available to Premium Service Members only.

Start your 7 day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
02.21.2008 at 04:09PM PST, ID: 20953422

All comments and solutions are available to Premium Service Members only.

Start your 7 day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
02.21.2008 at 07:11PM PST, ID: 20954249

All comments and solutions are available to Premium Service Members only.

Start your 7 day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
 
Loading Advertisement...
Microsoft
  • Internet Protocols
  • Applications
  • Development
  • OS
  • Hardware
  • Windows Security
Apple
  • Operating Systems
  • Hardware
  • Programming
  • Networking
  • Software
Internet
  • Search Engines
  • File Sharing
  • WebTrends / Stats
  • Spy / Ad Blockers
  • Web Browsers
  • New Net Users
  • Web Development
  • Chat / IM
  • Anti Spam
  • Web Servers
  • Anti-Virus
  • Email Clients
Gamers
  • Tips
  • Online / MMORPG
  • Puzzle
  • Emulators
  • Action / Adventure
  • Role Playing
  • Consoles
  • Game Programming
  • Strategy
  • Sports
  • Misc
  • Computer Games
Digital Living
  • Hardware
  • New Net Users
  • New Users
  • Software
  • Digital Music
  • Gaming World
  • Home Security
  • Apple
  • Networking Hardware
Virus & Spyware
  • Vulnerabilities
  • IDS
  • Encryption
  • Anti-Virus
  • Operating Systems Security
  • Software Firewalls
  • WebApplications
  • Cell Phones
  • Operating Systems
  • Internet
  • Hardware Firewalls
Hardware
  • Handhelds / PDAs
  • Displays / Monitors
  • Components
  • Networking Hardware
  • Peripherals
  • Laptops/Notebooks
  • Storage
  • Servers
  • Desktops
  • New Users
  • Misc
  • Apple
Software
  • System Utilities
  • Industry Specific
  • Network Management
  • Photos / Graphics
  • Page Layout
  • VMWare
  • Misc
  • Web Development
  • OS
  • CYGWIN
  • Voice Recognition
  • Message Queue
  • Quality Assurance
  • Security
  • Firewalls
  • MultiMedia Applications
  • Development
  • Database
  • Office / Productivity
  • Business Management
  • OS/2 Apps
  • Server Software
  • Internet / Email
ITPro
  • OS
  • Storage
  • Encryption
  • Operating Systems Security
  • Apple Hardware
  • Laptops & Notebooks
  • Servers
  • Networking Hardware
  • Peripherals
  • Devices
  • Displays / Monitors
  • WebTrends / Stats
  • Search Engines
  • Firewalls
  • WebApplications
  • IDS
  • Vulnerabilities
  • Email Clients
  • File Sharing
  • Spy / Ad Blockers
  • Web Browsers
  • Web Servers
  • Networking
  • Anti-Virus
  • Chat / IM
  • Anti Spam
Developer
  • Web Servers
  • Web Browsers
  • Game Programming
  • Dev Tools
  • Industry Specific
  • Office / Productivity
  • Database
  • CYGWIN
  • Web Development
  • Search Engines
  • File Sharing
  • WebTrends / Stats
  • Programming
  • Content Management
  • Application Servers
  • Protocols
Storage
  • Removable Backup Media
  • Storage Technology
  • Servers
  • Grid
  • Remote Access
  • Backup / Restore
  • Misc
  • Hard Drives
OS
  • Miscellaneous
  • Security
  • Development
  • Linux
  • VMWare
  • MainFrame OS
  • Unix
  • Apple
  • OS / 2
  • AS / 400
  • BeOS
  • Microsoft
  • VMS / OpenVMS
Database
  • Oracle
  • Miscellaneous
  • MySQL
  • Software
  • Sybase
  • Contact Management
  • PostgreSQL
  • Data Manipulation
  • Clarion
  • InterSystems Cache
  • Siebel
  • MUMPS
  • OLAP
  • SQLBase
  • SAS
  • GIS & GPS
  • 4GL
  • Berkeley DB
  • DB2
  • Informix
  • Interbase / Firebird
  • FoxPro
  • Reporting
  • LDAP
  • Filemaker Pro
  • MS SQL Server
  • dBase
  • MS Access
Security
  • Misc
  • Web Browsers
  • Software Firewalls
  • Operating Systems Security
  • File Sharing
  • Spy / Ad Blockers
  • Vulnerabilities
  • WebApplications
  • IDS
  • Anti-Virus
  • Encryption
  • Anti Spam
  • Email Clients
  • VPN
  • Chat / IM
Programming
  • Editors IDEs
  • Installation
  • Handhelds / PDAs
  • Multimedia Programming
  • System / Kernel
  • Algorithms
  • Game
  • Signal Processing
  • Project Management
  • Open Source
  • Database
  • Misc
  • Languages
  • Processor Platforms
  • Theory
Web Development
  • Scripting
  • Blogs
  • Web Servers
  • Software
  • Search Engines
  • Web Graphics
  • Images
  • Internet Marketing
  • Images and Photos
  • Components
  • Document Imaging
  • Web Languages/Standards
  • Illustration
  • WebApplications
  • Fonts
  • WebTrends / Stats
  • Authoring
  • Digital Camera Software
  • Miscellaneous
Networking
  • Protocols
  • Apple Networking
  • Network Management
  • Message Queue
  • Application Servers
  • Content Management
  • File Servers
  • Email Servers
  • Misc
  • Java Editors & IDEs
  • Wireless
  • Networking Hardware
  • Backup / Restore
  • System Utilities
  • ISPs & Hosting
  • Web Servers
  • Storage Technology
  • Removable Backup Media
  • Servers
  • Broadband
  • Grid
  • OS / 2
  • Novell Netware
  • Unix Networking
  • Windows Networking
  • Security
  • Telecommunications
  • Operating Systems
  • Linux Networking
Other
  • Community Advisor
  • Lounge
  • Community Support
  • New Net Users
  • Philosophy / Religion
  • Math / Science
  • Miscellaneous
  • URLs
  • Expert Lounge
  • Politics
  • Puzzles / Riddles
Community Support
  • Suggestions
  • New to EE
  • New Topics
  • Community Advisor
  • CleanUp
  • Announcements
  • General
  • Feedback
  • Input
  • EE Bugs
 
02.21.2008 at 09:07AM PST, ID: 20949648

Rank: Genius

SELECT ''''
Assisted Solution
 
02.21.2008 at 09:25AM PST, ID: 20949848
ok, that probalby is going to be my answer, but I have a required followon.  WHY does that work?  that makes no sense.  that should return either '' or a blank empty string, not a single quote.

Is this a special rule built into the T-SQL interpreter, to forget parsing rules when there are four single quotes together, and return a single quote?  Maybe if you select ''''' it returns the machine name, eh?

grrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
 
02.21.2008 at 09:33AM PST, ID: 20949910

Rank: Genius

> WHY does that work?  
By default, whatever string you need to print, it must be included within single quotes, but if you put 3 singleQuotes, the compliler wont consider this as a single string and will wait for another quote which in fact will be the end of the string

For example
If youtry these 2 commands it will throw an error
SELECT '''
GO
cause there is no concept of a single quote alone. so it will consider GO also as a part of the above query and will waitfor another single quote
 
02.21.2008 at 09:52AM PST, ID: 20950065
aneeshattingal, thank you for taking a shot, but I don't think that explains it.  

Seems to me, select '''' should return either '' or empty string.  There is no single quote enclosed by anything.  Why doesn't the interpreter see '''' as two consecutive empty strings?  maybe if I select dogdogdogdog  I will get get dog back?

Here is what would make sense:
select "'"

That is a double quote, followed by a single quote, then closed with a double.

But, for no good reason, T-SQL does not handle double quotes, so we are left with a non-sensible system of single quotes.

This makes me mad.  
 
02.21.2008 at 10:18AM PST, ID: 20950317
Unfortunately, aneeshattingal is correct. To 'escape' the single quote, add an additional single quote. I agree with you:  it does not make sense and it is a serious drawback to SQL Server.  

The workaround of doubling up the single quote is not human readable -- for me at least it is not readable --  and, therefore,  highly error prone.  Others seem to have better eyesight than I have and can count to 4 more consistently.  What I do (you're not going to like this either) is to add the ascii character so that I can see it. For example

SET @FieldValueFromName = char(39) + 'Agriculture' + char(39)
SELECT @FieldValueFromName returns 'Agriculture'

I usually set the single quote (aka apostrophe or tick mark) as a variable to make it even more readable.

Not a good solution, but it is an improvement for me.
Accepted Solution
 
02.21.2008 at 11:02AM PST, ID: 20950729

Rank: Genius

>> To 'escape' the single quote, add an additional single quote. I agree with you:  it does not make sense and it is a serious drawback to SQL Server. <<

It's true that it's somewhat awkward to look at, but I don't see what else you could do.  It's easier to see in something like this:

SELECT 'O''Brien'

What else can they do?  Otherwise yhey would have to designate an escape character, and that is just about as awkward.  Why would:

SELECT 'O~'Brien' ESCAPE '~'

or the equivalent really be any better?
 
02.21.2008 at 12:12PM PST, ID: 20951401
I would prefer a function to escape the whole string at one time like I can get in Javascript or php.
 
02.21.2008 at 01:36PM PST, ID: 20952100

Rank: Genius

You can use QUOTENAME().
Assisted Solution
 
02.21.2008 at 03:04PM PST, ID: 20952844
ScottPletcher:  My respects and appreciation for your bringing this up.  It looks like QUOTENAME() is a legitimate path.  However, my basic gripe is this should be a total no-brainer process.  I admit to being dim, so it took me reading all the way through this description from MSDN, before I found enough info to say for sure.  This is hardly no-brainer.  


******************************************************************
SQL Server 2005 Books Online (September 2007)
QUOTENAME (Transact-SQL)

Returns a Unicode string with the delimiters added to make the input string a valid Microsoft SQL Server 2005 delimited identifier.

QUOTENAME ( 'character_string' [ , 'quote_character' ] )

 Arguments

' character_string '

    Is a string of Unicode character data. character_string is sysname.

' quote_character '

    Is a one-character string to use as the delimiter. Can be a single quotation mark ( ' ), a left or right bracket ( [ ] ), or a double quotation mark ( " ). If quote_character is not specified, brackets are used.
http://msdn2.microsoft.com/en-us/library/ms176114.aspx
********************************************************************************************

fesnyng:  Obviously, you are going to score, because you expressed agreement with me, while I am flaming.  Hell, I'll follow you to war now.

On more serious note, thank you for understanding and explaining.  I had been thinking about using the ASCII solution.... and.. of course I have the ASCII character codes memorized, of course.  ** rolling eyes **  Then, you made my day, by posting not only the correct codes, but an example of to embed them in the type of code I am working on!  This makes you the most awesome question answerer I ever saw.  

aneeshattingal:  Your answer was perfect.  You are getting the original 65 points and the graded answer, since you were first, and it worked as soon as I tried it.  Plus, it gets infinite style points for brevity.  Nothing like the short, perfect answer in the heat of hurried situation to improve a day at the office.  Once I had your answer, I knew I could get done what I needed.  I have indulged in this thread as a way of reinforcing whatever I need to learn, so I  never need to suffer this particular hell again, of being confounded by the most basic T-SQL on a short fuse.  I don't mind puzzles, but irrational puzzles when I am short on time are a bummer to me.

ScottPletcher (again).  The O'Brien is a great example for lots of purposes.  My compliments again, for providing this tidbit.  I'll remember O'Brien.

Back to quotename, I noticed the default delimiter for strings is square bracket.  The problem with any delimiter is the string might contain the delimiter, no matter what it is.  I suppose you could avoid the problem by delimiting strings with something that is not a string, or a string that would be guaranteed excluded from the string.  These rules would allow unambiguous processing of delimited strings.  

If a string can include the string-delimiter, this problem always has potential to exist.

Picking ' as the default string delimter is retarded, since ' is a common string value in English.  Same can be said for square brackets, though to a lesser extent.  Maybe this is why unix people use the ` , which I never really have understood, except as an interference in my Windows-based activity.  

I guess among all the options I can think of, '''' is as good as any.  It's short, easy to remember.  If we added a special new character that somehow could not be in any string, adoption might be a bummer, with the payoff being that only people like us have slightly easier work lives.

Here is the thing though... I do this sort of programming with PHP/MySQL all the time, and I never have this sort of problem.  There is something odd about the T-SQL interpreter.  It would take me awhile to reproduce, but I saw it when I was going through a matrix of syntax variations trying to find one that would work.  T-SQL could see either @FieldValue or Agriculture, but not 'Agriculture'   I never have this problem in PHP/MySQL.

I have a feeling the best info on this issue lies in understand how Unix does certain things better than Windows at this string parsing level.

fesnyng:  I have a feeling your comments are 100% on the money.  If quotename() is t-sql's answer for how things work in php/mysql, then I don't understand why I never have been confused by php/mysql, but T-sql repeatedly proves 100% effective, but requires weird functions and strings, with the letter N thrown in oddly for good measure.  If I am misguided on this, it's worth points for someone to help me see that.


POINTS ON THE BOARD

aneeshattingal: 65 points, with gold star for perfect brevity and elegance in responding

ScottPletcher: 85 points for agreeing with me and providing the best solution available today

fesnyng:  50 points for putting php on the table

still available:  50 points for explaining how/why t-sql is stupid compared to php/javascript/mysql.

potential bonus:  50 bonus points if answer to above question is stupendously awesome, as has been the case in this thread already.


 
02.21.2008 at 03:14PM PST, ID: 20952898
I think the edge held by php, allowing it to avoid this problem, is it allows either single or double quotation marks.  With nesting, you always can tell the interpreter what you want in a logical manner.  It is not always simple, but it logical, and definitely simpler than some of the gymnastics I have been forced into by t-sql over the single quote issue.  Example, shows complications better than this question, is at:
http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/SQL-Server-2005/Q_23179246.html  

The same coding in php is totally simple compared this
exec sp_executesql @sql, N'@res INT OUTPUT' , @LookupKeyFieldValue OUTPUT  

I look at that and say,,,, ok, whatever.  What I had before was a lot simpler, and works just fine, except in the case where the @sql string has to be comprised of values read from variables... for no good reason, using variables to build the @SQL leads to use of a strange looking function that says output twice.  On top of that, random string delimiter rules complicate further.

Why doesn't t-sql allow use of double quotes as a string delimiter?
 
02.21.2008 at 03:27PM PST, ID: 20953012
CORRECTION (had wrong name on this):
ScottPletcher:  Obviously, you are going to score, because you expressed agreement with me, while I am flaming.  Hell, I'll follow you to war now.

On more serious note, thank you for understanding and explaining.  I had been thinking about using the ASCII solution.... and.. of course I have the ASCII character codes memorized, of course.  ** rolling eyes **  Then, you made my day, by posting not only the correct codes, but an example of to embed them in the type of code I am working on!  This makes you the most awesome question answerer I ever saw.  

Points are correct.
POINTS ON THE BOARD

aneeshattingal: 65 points, with gold star for perfect brevity and elegance in responding

ScottPletcher: 85 points for agreeing with me and providing the best solution available today

fesnyng:  50 points for putting php on the table

still available:  50 points for explaining how/why t-sql is stupid compared to php/javascript/mysql.

potential bonus:  50 bonus points if answer to above question is stupendously awesome, as has been the case in this thread already.
 
02.21.2008 at 04:09PM PST, ID: 20953422

>> I think the edge held by php, allowing it to avoid this problem, is it allows either single or double quotation marks.  <<

Give yourself the 50points for getting the right answer.  Also, thanks to ScottPletcher for pushing me to think a little more about this with the QUOTENAME answer.  That really helped me think more clearly about this.

Also, I have been working with the exact same issue that you have for the past 2 days.  So, I was more than in agreement with you.  I had 'settled' for the ASCII solution.  It has been tedious.   The php-style answer is ...

SET QUOTED_IDENTIFIER OFF

This will allow you to use the double quotes to encapsulate the single quotes ... just like php.

For example...

SET QUOTED_IDENTIFIER OFF
SET @sql = " SELECT   'Agriculture'   "
EXEC (@sql) --returns 'Agriculture'
SET QUOTED_IDENTIFIER ON



Assisted Solution
 
02.21.2008 at 07:11PM PST, ID: 20954249
POINTS ON THE BOARD

aneeshattingal: 65 points, with gold star for perfect brevity and elegance in responding

fesnyng: 85 points for agreeing with me and providing the best solution available today <-- I kept mixing up who said this, because scott quoted fesnyng.

fesnyng:  50 points for putting php on the table

Scott:  20  points for quotename(), the O'Brien example

fesnyng:  30 points for being a good sport when I kept goofing up credit.
 
 
02.21.2008 at 07:42PM PST, ID: 20954381
Thanks for making it fun.  Hope you got what you needed, too.
 
 
05.04.2008 at 01:04AM PDT, ID: 21494927
I will put some additional comment on this quite aged thread :-)

To add quotes you can of course user QUOTENAME function but...

Remember that QUOTENAME gets ____SYSNAME____ as the first parameter. And if your string to quote is above 128 characters long then QUOTENAME will return NULL which may be quite unexpected result in some cases :-)

Best Regards folks ;-)
 
 
 
20080236-EE-VQP-29 / EE_QW_2_20070628