4

I have a Column having Image datatype in MS-SQL SERVER 2012. I want to get it as string in SQL Query..

I have Tried This:

SELECT 
'empphoto : '+ ISNULL(CONVERT(VARCHAR(MAX), CONVERT(VARBINARY(MAX), empphoto)),'') 
from emppersonal where --some condition

--empphoto Columns is of Image datatype

output looks corrupted (Just 4 characters).

OutPut looks like:

empphoto : ÿØÿà

enter image description here

How can be an Image datatype be converted to string in MS-SQL Server?

2
  • 1
    What are you actually trying to do? Commented Dec 1, 2014 at 8:24
  • Before Updating Any row in table, I have to save that row data along with column name in some another table as a single string Commented Dec 1, 2014 at 8:45

1 Answer 1

11

You can extract the image value as BASE64 by running it through for xml path().

Try:

select 'empphoto : '+(select empphoto as '*' for xml path(''))

Result will look something like this.

empphoto : /9j/4AAQSkZJRgABAQAAAQABAAD/wAARCADw

To go the other way you have to remove the first 11 characters (empphoto :), cast to XML and extract the value as varbinary(max)..

select cast(stuff(YourTextColumn, 1, 11, '') as xml).value('.', 'varbinary(max)')
Sign up to request clarification or add additional context in comments.

5 Comments

ok,..If I have to insert it back to the same column empphoto Image datatype then how to cast it back
It looks working for varbinry(max) conversion. and not for Image datatype conversion
If I have to insert it back to the same column empphoto which is of Image datatype not varbinary(max).Then shouldn't I need to cast to Image datatype instead of varbinary(max) as done above
@user3879765 There is an implicit conversion from varbinary(max) to image. Have you tried it? You should not change the code that extract the data. Keep varbinary(max) in there and an insert to an image field should work just fine. If not you have to show the code you use with table structures and the error message you get.
@user3879765 To remove the implicit conversion you can do an explicit conversion instead. cast(cast(stuff(YourTextColumn, 1, 11, '') as xml).value('.', 'varbinary(max)') as image)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.