Wednesday, February 8, 2012

Junk data when convert binary to string

Here is the example :
Step 1: when I convert this string to binary I got the below output.
SELECT CONVERT(varbinary(max), '(DAYSBETWEENREADINGS(''SNOT'') * 100 / 365)')
Output:
0x28444159534245545745454E52454144494E47532827534E4F542729202A20313030202F2033363529

But in the table from which I am trying to convert binary to string I am having other than this, but sql server still returning the same string.

select CONVERT(varchar(max), 0x28444159534245545745454E52454144494E47532827534E4F542729202A20313030202F203336352900080030000000000000000000000000000000FFFF010000001C0001000000000000000000000000000000060007002A0000000000000000000000000000000100030000002B000200000000000000000000000000020000000000280001000000000000000000000000000100020000001A0000000000000000005940000000000100000000001B0001000000000000000000000000000100040005001A0000000000000000D076400000000001000000000002002800000000000000000000002B00140000000000000000001900444159534245545745454E52454144494E475300534E4F540000)
OutPut:
(DAYSBETWEENREADINGS('SNOT') * 100 / 365)


How to truncate the unnecessary sequence from binary data?


Solution :

For i = 0 To ds.Tables(t).Rows.Count - 1
                    dr = dt.NewRow()
                    For j As Integer = 0 To ds.Tables(t).Columns.Count - 2
                        If Not IsDBNull(ds.Tables(t).Rows(i)(j)) Then
                            If ds.Tables(t).Columns(j).DataType.Name = "Byte[]" Then

                                ss = "select convert(varchar(max),convert(varbinary(max),@byteArray)) as binarystr;"
                                cmd = New SqlCommand(ss.ToString, conn)
                                da1 = New SqlDataAdapter(cmd)
                                commonds = New DataSet
                                cmd.Parameters.Add("@byteArray", Data.SqlDbType.Image).Value = ds.Tables(t).Rows(i)(j)
                                da1.Fill(commonds)
                                If commonds.Tables(0).Rows.Count > 0 Then
                                    binarystr = commonds.Tables(0).Rows(0).Item(0)
                                    dr(j) = binarystr.Substring(0, binarystr.IndexOf(vbNullChar)) ‘We just done the substring, with the vbnullchar.

                                End If
                            Else
                                dr(j) = ds.Tables(t).Rows(i)(j)
                            End If
                        End If
                        commonds.Dispose()
                    Next
                    dt.Rows.Add(dr)
                Next
            Next
                     DataGridView1.DataSource = dt

No comments:

Post a Comment