Initialize Varbinary datatype in MySQL - mysql

In MySQL, I want to declare a default value to a varbinary column. How do I achieve it ?
DECLARE result varbinary(8000);
SET result = 0x;
I used select CHAR_LENGTH(00101) and it gives me a result 3. I am expecting my result to be 5 (number of characters in string). To measure the length of a varbinary string, how do I do it ?

When you create your table you can specify a default. For binary data you should probably express it as a hex string, 0x... style:
CREATE TABLE binary_default (
id INT PRIMARY KEY AUTO_INCREMENT,
binary_data VARBINARY(8000) DEFAULT 0x010203
);
You can test this works with:
INSERT INTO binary_default VALUES ()
Then fetch, but as it's binary, you might want a hex view:
SELECT id, HEX(binary_data) FROM binary_default

Related

Why * is Inserted in SQL

This happened when I was just testing.
I've created a table as
Create Table Test_Table
(
Field_char char(1)
);
When I want to insert value with code
Insert Into Test_Table(Field_char)
Select 13;
It inserts '*' in the column. For single digits it inserts them as it is. If the length is modified from 1 to 2, similar thing happen for 3 digits input such as 100 etc.
Why is this?
In your create statement you set the length of Field_char to 1 (char(1)). This means that your entries must have a length smaller or equal to 1. valid entries are 1,2 etc. Invalid entries are 12, 13 as they are longer than 1 char -> * is a placeholder to indicate invalid values.
EDIT: (Thanks To Vladimir)
To be more precise take a look here.
Truncating and Rounding Results
[...] Conversions to char, varchar, nchar, nvarchar, binary, and varbinary are truncated, except for the conversions shown in the following table.
There we have the following entry:
From data type int to data type char result *
where * = Result length too short to display
When you are writing
Insert Into Test_Table(Field_char)
Select 13;
The it is converting int to char. So your 13 is converted into *. If you want you can check by writing
select CONVERT(char(1),13)
If you want to see the result as 13 then you need to put that in single inverted comma like this:
Insert Into Test_Table(Field_char)
Select '13';
And also you need to increase the size of column as char(1) can hold only one character.
SQL FIDDLE DEMO
It simply Convert Int to Char
for Example
select CONVERT(char(1),13)
it will give *
Sql Implicitly convert int to char which is you column type..

Conversion error with NULL column and SELECT INTO

I'm experimenting with temporary tables and running into a problem.
Here's some super-simplified code of what I'm trying to accomplish:
IF(Object_ID('tempdb..#TempTroubleTable') IS NOT NULL) DROP TABLE #TempTroubleTable
select 'Hello' as Greeting,
NULL as Name
into #TempTroubleTable
update #TempTroubleTable
set Name = 'Monkey'
WHERE Greeting = 'Hello'
select * from #TempTroubleTable
Upon attempting the update statement, I get the error:
Conversion failed when converting the varchar value 'Monkey' to data type int.
I can understand why the temp table might not expect me to fill that column with varchars, but why does it assume int? Is there a way I can prime the column to expect varchar(max) but still initialize it with NULLs?
You need to cast null to the datatype because by default its an int
Select 'hello' as greeting,
Cast (null as varchar (32)) as name
Into #temp

Why is AES_DECRYPT returning null?

I've found similar questions, but no clear answer for this question. I have this table:
CREATE DATABASE testDB DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
CREATE TABLE testTable
(
firstName binary(32) not null,
lastName binary(32) not null
/* Other non-binary fields omitted */
)
engine=INNODB DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
This statement executes just fine:
INSERT INTO testTable (firstName) VALUES (AES_ENCRYPT('Testname', 'test'));
But, this returns NULL:
SELECT AES_DECRYPT(firstName, 'test') FROM testTable;
Why does this return NULL?
Fwiw, this returns "testValue" as expected:
SELECT AES_DECRYPT(AES_ENCRYPT('testValue','thekey'), 'thekey');
The answer is that the columns are binary when they should be varbinary. This article explains it:
Because if AES_DECRYPT() detects invalid data or incorrect
padding, it will return NULL.
With binary column types being fixed length, the length of the input value must be known to ensure correct padding. For unknown length values, use varbinary to avoid issues with incorrect padding resulting from differing value lengths.
When you insert binary data into a VARCHAR field there are some binary characters that a VARCHAR can't handle and they will mess up in the inserted value. And then the inserted value will not be the same when you retrieve it.
1.select hex(aes_encrypt(file,'key'));
2.select aes_decrypt(unhex(file),'key');
Check if type of your field is blob instead binary(32)
Did you try different values other than 'Testname'?
Do other values work?
I ask because I had a situation while testing 2 test credit card numbers where one decrypted fine and the other returned null.
The answer was to hex and unhex as suggested by "abhinai raj"

Convert char(5) to tinyint(4) in mysql

I'm trying to insert rows from one table to the other. In the first table, the datatype of one column is char(5), but the same column has tinyint(4) datatype in the second table. When i run the insert query, it says
Incorrect integer value: '' for column 'x' at row 258
I cannot alter or modify the datatype now as it violates some constraints. Is there a way to use cast or convert char to tinyint?
Thanks.
You probably want something like this:
INSERT INTO newtable
SELECT CASE WHEN x = '' THEN 0 ELSE x END
FROM oldtable
I'm assuming that you want blanks to turn into zeros? If not, then provide the integer value you want blanks to have.
If there are other exceptions, use more alternatives in the CASE expression.

MySql insert statement to binary datatype?

I am using MySQL database.
I have one table having column with datatype binary(16).
I need help with the insert statement for this table.
Example:
CREATE TABLE `assignedresource` (
`distid` binary(16) NOT NULL
)
insert into assignedresource values ('9fad5e9e-efdf-b449');
Error : Lookup Error - MySQL Database Error: Data too long for column 'distid' at row 1
How to resolve this issue?
You should remove the hyphens to make the value match the length of the field...
Example:
CREATE TABLE `assignedresource` (
`distid` binary(16) NOT NULL
)
insert into assignedresource values ('9fad5e9eefdfb449');
Also, MySQL standard is to use this notation to denote the string as binary... X'9fad5e9eefdfb449', i.e.
insert into assignedresource values (X'9fad5e9eefdfb449');
Well, assuming that you want to strictly insert a hexadecimal string, first you need to remove the dashes and then "unhex" your string before inserting it into a binary(16) data type column, the code would go like this:
INSERT INTO `assignedresource` VALUES(UNHEX(REPLACE('9fad5e9e-efdf-b449','-','')));
Also... the "usable" data you are inserting is actually 8 bytes after undashing it, so binary(8) would do fine if you plan on not storing the dashes.
You can strip the hyphens and perpend 0x to the value unquoted, like this:
insert into assignedresource values (0x9fad5e9eefdfb449);
As well as, as this (mentioned in other answers):
insert into assignedresource values (X'9fad5e9eefdfb449');
Both are valid notation for a hexadecimal literal.
Your string is 18 char long, change the database
CREATE TABLE `assignedresource` (
`distid` binary(18) NOT NULL
)