Created
October 13, 2022 22:58
-
-
Save tomfa/edc5bc996500eee4aaae941eb2f54f90 to your computer and use it in GitHub Desktop.
Parse T-SQL binary field with Python and save as file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import csv | |
import sys | |
# Can be required if files are large | |
csv.field_size_limit(sys.maxsize) | |
def parse_hex(val: str): | |
return bytes.fromhex(val) | |
def convert(output_path: str): | |
with open('./Records.csv') as csvfile: | |
lines = csv.DictReader(csvfile, delimiter=',') | |
for row in lines: | |
hexdata = row['data'].replace('0x', '') # feels a bit hacky | |
if len(data_list) % 2: | |
print('Warning: Found a potential partial file. SQL export might have truncated the file column') | |
data = bytes.fromhex(data_list) | |
with open(row['id'], 'wb') as f: | |
f.write(data) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SELECT [id] | |
,[data] | |
-- Uncomment the hack below if data fields are truncated | |
-- ,cast(convert(varchar(max), [data], 1) as xml) as data | |
FROM [dbo].[FileTable]; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
id | data | |
---|---|---|
1 | 0x2550 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment