Skip to content

Instantly share code, notes, and snippets.

@tomfa
Created October 13, 2022 22:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomfa/edc5bc996500eee4aaae941eb2f54f90 to your computer and use it in GitHub Desktop.
Save tomfa/edc5bc996500eee4aaae941eb2f54f90 to your computer and use it in GitHub Desktop.
Parse T-SQL binary field with Python and save as file
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)
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];
id data
1 0x2550
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment