Can't get a full length of binary data from SSMS - sql-server

Table
id - int
file - varbinary(max)
Query
SELECT file
FROM Table
WHERE id = 1
Data
The id 1 data has a file. And it's binary length is 836,412. But when I run the query, I only see a 43,680 bytes of binary data.
I tried to download the data as a CSV through "Save Result as..." button in the pop up panel. But still, I couldn't get a full length of the binary data.
In the CSV, there's only 16 bit (unsigned, 65534 length) data available. Unfortunately, I cannot request the data from my application at this moment. I have to pull it out from SSMS and convert it manually in my test code to see the file.
How can I get the full binary data from SSMS? Is there an option for displaying full length of binary data?

You can try casting the "file" field to XML using a query such as the following...
SELECT CAST(CONVERT(VARCHAR(MAX), file, 1) AS XML)
FROM Table
WHERE id = 1
However, you'll need to confirm that your SSMS Query options are set appropriately:
Query | Query Options... | Results | Grid | XML Data: unlimited
This will provide your results in hex, like so:
0x47494638396150003200F70 ...

Related

Converting data in column in SSIS

I'm writing an SSIS package to load data from a .csv into a db.
There's a column in the csv file that is supposed to have a count, but the records sometimes have text, so I can't just load the data in as an integer. It looks something like this:
I want the data to land in the db destination as an integer instead of a string. I want the transformation to change any text to a 1, any blank value to a 1, and leave all the other numbers as-is.
My attempts have so far included using the Derived Column functionality, which I couldn't get the right expression(s) for it seems, and creating a temp table to run a sql query through the data, which kept breaking my data flow.
There are three approaches you can follow.
(1) Using a derived column
You should add a derived column with the following expression to check if the values are numeric or not:
(DT_I4)[count] == (DT_I4)[count] ? [count] : 1
Then in the derived column editor, go to the error output configuration and set the error handling event to Ignore failure.
Now add another derived column to replace null values with 1 :
REPLACENULL([count_derivedcolumn],1)
You can refer to the following article for a step-by-step guide:
Validate Numeric or Non-Numeric Data in SQL Server Integration Services without the Script Task
(2) Using a script component
If you know C# or Visual Basic.NET, you can add a script component to check if the value is numeric and replace nulls and string values with 1
(3) Update data in SQL
You can stage data in its initial form into the SQL database and use an update query to replace nulls and string values with 1 as follows:
UPDATE [staging_table]
SET [count] = 1
WHERE [count] IS NULL or ISNUMERIC([count]) = 0

SQL query result truncated [duplicate]

How do you view ALL text from an NTEXT or NVARCHAR(max) in SQL Server Management Studio? By default, it only seems to return the first few hundred characters (255?) but sometimes I just want a quick way of viewing the whole field, without having to write a program to do it. Even SSMS 2012 still has this problem :(
I was able to get the full text (99,208 chars) out of a NVARCHAR(MAX) column by selecting (Results To Grid) just that column and then right-clicking on it and then saving the result as a CSV file. To view the result open the CSV file with a text editor (NOT Excel). Funny enough, when I tried to run the same query, but having Results to File enabled, the output was truncated using the Results to Text limit.
The work-around that #MartinSmith described as a comment to the (currently) accepted answer didn't work for me (got an error when trying to view the full XML result complaining about "The '[' character, hexadecimal value 0x5B, cannot be included in a name").
Quick trick-
SELECT CAST('<A><![CDATA[' + CAST(LogInfo as nvarchar(max)) + ']]></A>' AS xml)
FROM Logs
WHERE IDLog = 904862629
In newer versions of SSMS it can be configured in the (Query/Query Options/Results/Grid/Maximum Characters Retrieved) menu:
Old versions of SSMS
Options (Query Results/SQL Server/Results to Grid Page)
To change the options for the current queries, click Query Options on the Query menu, or right-click in the SQL Server Query window and select Query Options.
...
Maximum Characters Retrieved
Enter a number from 1 through 65535 to specify the maximum number of characters that will be displayed in each cell.
Maximum is, as you see, 64k. The default is much smaller.
BTW Results to Text has even more drastic limitation:
Maximum number of characters displayed in each column
This value defaults to 256. Increase this value to display larger result sets without truncation. The maximum value is 8,192.
I have written an add-in for SSMS and this problem is fixed there. You can use one of 2 ways:
you can use "Copy current cell 1:1" to copy original cell data to clipboard:
http://www.ssmsboost.com/Features/ssms-add-in-copy-results-grid-cell-contents-line-with-breaks
Or, alternatively, you can open cell contents in external text editor (notepad++ or notepad) using "Cell visualizers" feature: http://www.ssmsboost.com/Features/ssms-add-in-results-grid-visualizers
(feature allows to open contents of field in any external application, so if you know that it is text - you use text editor to open it. If contents is binary data with picture - you select view as picture. Sample below shows opening a picture):
Return data as XML
SELECT CONVERT(XML, [Data]) AS [Value]
FROM [dbo].[FormData]
WHERE [UID] LIKE '{my-uid}'
Make sure you set a reasonable limit in the SSMS options window, depending on the result you're expecting.
This will work if the text you're returning doesn't contain unencoded characters like & instead of & that will cause the XML conversion to fail.
Returning data using PowerShell
For this you will need the PowerShell SQL Server module installed on the machine on which you'll be running the command.
If you're all set up, configure and run the following script:
Invoke-Sqlcmd -Query "SELECT [Data] FROM [dbo].[FormData] WHERE [UID] LIKE '{my-uid}'" -ServerInstance "database-server-name" -Database "database-name" -Username "user" -Password "password" -MaxCharLength 10000000 | Out-File -filePath "C:\db_data.txt"
Make sure you set the -MaxCharLength parameter to a value that suits your needs.
I was successful with this method today. It's similar to the other answers in that it also converts the contents to XML, just using a different method. As I didn't see FOR XML PATH mentioned amongst the answers, I thought I'd add it for completeness:
SELECT [COL_NVARCHAR_MAX]
FROM [SOME_TABLE]
FOR XML PATH(''), ROOT('ROOT')
This will deliver a valid XML containing the contents of all rows, nested in an outer <ROOT></ROOT> element. The contents of the individual rows will each be contained within an element that, for this example, is called <COL_NVARCHAR_MAX>. The name of that can be changed using an alias via AS.
Special characters like &, < or > or similar will be converted to their respective entities. So you may have to convert <, > and & back to their original character, depending on what you need to do with the result.
EDIT
I just realized that CDATA can be specified using FOR XML too. I find it a bit cumbersome though. This would do it:
SELECT 1 as tag, 0 as parent, [COL_NVARCHAR_MAX] as [COL_NVARCHAR_MAX!1!!CDATA]
FROM [SOME_TABLE]
FOR XML EXPLICIT, ROOT('ROOT')
PowerShell Alternative
This is an old post and I read through the answers. Still, I found it a bit too painful to output multi-line large text fields unaltered from SSMS. I ended up writing a small C# program for my needs, but got to thinking it could probably be done using the command line. Turns out, it is fairly easy to do so with PowerShell.
Start by installing the SqlServer module from an administrative PowerShell.
Install-Module -Name SqlServer
Use Invoke-Sqlcmd to run your query:
$Rows = Invoke-Sqlcmd -Query "select BigColumn from SomeTable where Id = 123" `
-MaxCharLength 2147483647 -ConnectionString $ConnectionString
This will return an array of rows that you can output to the console as follows:
$Rows[0].BigColumn
Or output to a file as follows:
$Rows[0].BigColumn | Out-File -FilePath .\output.txt -Encoding UTF8
The result is a beautiful un-truncated text written to a file for viewing/editing. I am sure there is a similar command to save back the text to SQL Server, although that seems like a different question.
EDIT: It turns out that there was an answer by #dvlsc that described this approach as a secondary solution. I think because it was listed as a secondary answer, is the reason I missed it in the first place. I am going to leave my answer which focuses on the PowerShell approach, but wanted to at least give credit where it was due.
If you only have to view it, I've used this:
print cast(dbo.f_functiondeliveringbigformattedtext(seed) as text)
The end result is that I get line feeds and all the content in the messages window of SMSS.
Of course, it only allows for a single cell - if you want to do a single cell from a number of rows, you could do this:
declare #T varchar(max)=''
select #T=#T
+ isnull(dbo.f_functiondeliveringbigformattedtext(x.a),'NOTHINGFOUND!')
+ replicate(char(13),4)
from x -- table containing multiple rows and a value in column a
print #T
I use this to validate JSON strings generated by SQL code. Too hard to read otherwise!
Use visual studio code with sql server plugin. Super usefull for jsons
Alternative 1: Right Click to copy cell and Paste into Text Editor (hopefully with utf-8 support)
Alternative 2: Right click and export to CSV File
Alternative 3: Use SUBSTRING function to visualize parts of the column. Example:
SELECT SUBSTRING(fileXml,2200,200) FROM mytable WHERE id=123456
The easiest way to quickly view large varchar/text column:
declare #t varchar(max)
select #t = long_column from table
print #t

Convert a large SQL Server table to XML

I have a large table in SQL Server 2008 with roughly 500000 records and 40 columns. Some columns are string and they contain \n and other symbols. I want to convert this table to an XML file for use in project. When I use FOR XML to export this table, some errors are shown.
For example, when test:
select testData.*
from testData
FOR XML PATH('sample'), Type, ELEMENTS, ROOT(TestData')
only 3500 records are converted to XML and also, final element (that is record 3500) is not complete.
When test (without Type):
select testData.*
from testData
FOR XML PATH('sample'), ELEMENTS, ROOT(TestData')
All the records are converted to XML but some CR/LF character are added to the XML file that failed xml file. So, some tag like Product split to prod CRLF uct.
I searched for a long time but no page was helpful.
If its a one-shot work, you can use the soft Altova XMLSpy, which is free during 30 days. The Altova mission kit suite contains a lot of tools like XML MapForce which can map a db to a xml.

MSSQL image data is returned as text

I am updating a CGI application that accesses an MSSQL 2008 database containing customer data. The database is managed by a third-party application, so I cannot change the data structure.
One of the tables ('guests') contains a column 'mug_shot' of type 'Image'. The column contains a JPEG image of each guest. When I retrieve data from this column, it always appears to be in text format. For example, when I perform the following query:
my $mugshotQuery = "SELECT TOP 1 mug_shot FROM guests where guest_no = ?";
my $mugshotStatementHandle = $dbh->prepare($mugshotQuery);
$mugshotStatementHandle->execute($guest_number);
and fetch the data:
my $mugshotHash = $mugshotStatementHandle->fetchrow_hashref();
$mugshotHash->{mug_shot} contains a hexadecimal representation of the JPEG binary data. Here is a shortened example:
ffd8ffe000104a46494600010101004c004c0000ffe1004245786966000049492a000800000002001a01050001000000260000001b0105000100000030000000000000007d3b8c0440420f000000ed168e0440420f000000ffdb0043000302020302020303030304030304050805050404050a070706080c0a0c0c0b0a0b0b0d0e12100d0e110e0b0b1016101113141515150c0f171816141812141514ffdb00430103040405040509050509140d0b0d1414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414ffc00011080156010003012200021101031101ffc4001f0000010501010101010100000000000000000102030405060708090a0bffc400b5100002010303020403050504040000017d01020300041105122131410613516107227114328191a1082342b1c11552d1f02433627282090a161718191a25262728292a3435363738393a434445464748494a535455565758595a636465666768696a737475767778797a838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae1e2e3e4e5e6e7e8e9eaf1f2f3f4f5f6f7f8f9faffc4001f0100030101010101010101010000000000000102030405060708090a0bffc400b51100020102040403040705040400010277000102031104052131061241510761711322328108144291a1b1c109233352f0156272d10a162434e125f11718191a262728292a35363738393a434445464748494a535455565758595a636465666768696a737475767778797a82838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae2e3e4e5e6e7e8e9eaf2f3f4f5f6f7f8f9faffda000c03010002110311003f00bd3dc482790798ff0078ff0011f5a68b9931feb1ff0033493f133f7f98ff003a6923d39aed48f997e63fed1267fd63
Therefore, my attempt to display the image fails:
print STDOUT "Content-type: image/jpeg\n";
print STDOUT "Content-length: \n\n";
binmode STDOUT;
print STDOUT $mugshotHash->{mug_shot};
The browser reports that the image is invalid. Why is the data returned as text/hexadecimal instead of binary data, and what can I do to fetch the binary data?
There is a flag to return image data in binary format:
$dbh->{syb_binary_images} = 1;
After I set this flag, the images are returned in the correct format. For good measure, I also used the following to make sure that the images are not truncated:
$dbh->{LongTruncOK} = 0;
$dbh->do("set textsize 1000000");

How to convert Binary data to text data?

How to convert binary data to text?
I have column called File names in test table with image datatype so when i am selecting the data from test table its showing the data for file names column is binary data i.e ('0x433A5C55736535').
Regards
Anji
I can't beleive nobody answered this. If it's image data you won't get anything readable. but in case it is text data in a binary field, you can do this:
select cast(DataColumn as varchar(MAX)) as DataAsText from [TableWithData];
'0x433A5C55736535' is not binary data, binary data is composed only with 0 and 1.
I think you need to use the defined functions of your test table to get the data you want, if you are in MySQL it's "Select * from file names"

Resources