Sunday, February 19, 2012

Add apostrophe to column in result set

I have a brain teaser for you all.

The end result: I need one of the columns in my result set (col2) to have a preceeding apostrophe (i.e., '001234 ).

The problem: I am building my query as a string and then using the EXEC() function to execute it. For example:
SET @.strSQL = 'SELECT col1, col2 FROM mytable'
EXEC(@.strSQL)

Just to tame any answers that might not be directed to the specific question, the query Must be built as a string and then executed.

I have been unable to obtain the solution and I am wondering if it is even possible?

TIADo you mean single quote?

Is this what you need?

declare @.sql as varchar(2000)

set @.sql = 'select ''' + companyname as [''name] from customers'
exec(@.sql)

set @.sql = 'select ''`'' + companyname from customers'
exec(@.sql)

:)|||Easy!


'SELECT (CHAR(39) + table.column) FROM table'

:)|||Select [''hi] From Table

to clarify, ' is a delimiter in sql, so you must use two of them to escape it.

Select [''e1234] From YourTable Where [''e1234] = 'SomeValue';

That's how to do it.

Enjoy

No comments:

Post a Comment