1

I've tried googling for a while and couldn't find anything, but apologies if this is really obvious.

I have a Boolean array that is always length 8 and I want to insert the corresponding binary value into a binary(1) field. I'm using SQL Server 2012.

Currently I convert it into a string, e.g "10100101", and create a query string that looks something like "INSERT INTO Table1 VALUES('10100101');" Also have been trying to get a SELECT statement equivalent "SELECT * FROM Table1 WHERE bin_val=10100101;"

When I execute the statement I always get a syntax error. I've tried multiple variations (e.g with/without quote marks etc and putting the number in different format e.g "0xA5") with no luck.

Any suggestions?

p.s Writing code in java

2 Answers 2

2

First, you will need to convert your binary based number to a decimal based one. Then, you can simply convert that value to the datatype BINARY. So, assuming that your string is always 8 bits long, you can try this:

DECLARE @BinaryNumber CHAR(8)
SET @BinaryNumber = '10100101'
INSERT INTO Table1
SELECT  CAST(SUBSTRING(@BinaryNumber,8,1)+
             SUBSTRING(@BinaryNumber,7,1)*2+
             SUBSTRING(@BinaryNumber,6,1)*4+
             SUBSTRING(@BinaryNumber,5,1)*8+
             SUBSTRING(@BinaryNumber,4,1)*16+
             SUBSTRING(@BinaryNumber,3,1)*32+
             SUBSTRING(@BinaryNumber,2,1)*64+
             SUBSTRING(@BinaryNumber,1,1)*128 AS BINARY(1))
Sign up to request clarification or add additional context in comments.

1 Comment

thanks! Got it to work for INSERT INTO statement. However can't get it to for the SELECT statement... my statement is this: "SELECT * FROM CASES WHERE bin_val=CAST(3 AS BINARY(1))" It says: Incorrect syntax near '='
0

I haven't worked on SQL Server but I think you need to something like

INSERT INTO Table1 VALUES( CAST(10100101  AS BINARY(1)) );

More info here
http://msdn.microsoft.com/en-us/library/ms188362.aspx

1 Comment

op needs to first convert 10100101 to a decimal based value

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.