Conditional data type conversion | SQL Server - sql-server-2008

I'm trying to create a simple case statement that would update the existing Total column which has numeric values to:
'A_1' if Total is less than 2 or 'B_2' if other values
UPDATE BASE_V1
SET TOTAL=
(CASE
WHEN TOTAL<2 THEN 'A_1'
ELSE 'B_2'
END
)
Error: Conversion failed when converting the varchar value 'B_2' to data type int
I tried using the convert function to change the datatype but doesn't work
UPDATE BASE_V1
SET TOTAL=
(CASE
WHEN TOTAL<2 THEN CONVERT(VARCHAR(10),'A_1')
ELSE CONVERT(VARCHAR(10),'B_2')
END
)

If Total is a varchar column, then you need to compare it to a string:
UPDATE BASE_V1
SET TOTAL=
(CASE
WHEN TOTAL<'2' THEN 'A_1'
ELSE 'B_2'
END
)
The TOTAL<2 forces SQL to try to implicitly convert all values of Total to an integer. Putting the 2 in single quotes makes it a string comparison.

Related

get 0 when emptyornull values else max(id) when column datatype is numeric in sql server

Hi I have one doubt in sql server
get 0 when emptyornull values else max(id) when column datatype i is numeric in sql server
Table : empid
CREATE TABLE [dbo].[empid](
[id] [numeric](11, 0) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[empid] ([id]) VALUES (NULL)
GO
INSERT [dbo].[empid] ([id]) VALUES (CAST(6 AS Numeric(11, 0)))
GO
based on above data I want output like below
id
6
I tried like below
select case when isnull( max(id),'')='' then cast (0 as numeric) else max(id end test from )
[Test].[dbo].[empid]
but above query is getting error
Msg 8114, Level 16, State 5, Line 9
Error converting data type varchar to numeric.
suppose no records in table then maxid will get 0
please tell me how to write a query to achive this task in sql server
You should use the COALESCE function that gives you the ability to replace a potential NULL with whatever you wish (0 in your current case) as so:
select coalesce(id, 0) as id from [dbo].[empid];
Why use ''? Just use 0:
SELECT ISNULL(id,0) AS test
FROM dbo.empid;
ISNULL returns the datatype of the first parameter, and with the SQL you had, you were therefore implicitly trying to convert '' to a numeric, which was failing.
The better way to do this is to use COALESCE function provided by SQL
COALESCE(arg1, arg2[, argN])
what it does is it takes N arguments
arg1 is a column that can be null
arg2 is a column that can be null
argN is the value that you want to replace it with
Query could be
SELECT COALESCE(Id, 0) as Id FROM [dbo].[empid]

Set mysql Zero date results to null or a blank string

I am using str_to_date() as part of an insert command on a field which either contains a correctly formatted date or a blank string.
For rows with a blank string str_to_date returns a ZERO date of '0000-00-00 00:00:00' as expected.
I can use the IGNORE keyword as part of the INSERT statement to prevent errors, but having the ZERO date in the table leads to issues later when attempting to compare the field to other vales. My goal is to insert either a blank string or a null value. Can anybody point me in the right direction?
One solution would be like this:
insert into mytable
select
case
when varchar_date != '' then str_to_date(varchar_date, 'date_format')
end as date_column,
...
from
...
(whenever varchar_date is not empty, call str_to_date function which will return a valid date if varchar_date is a valid string, and whenever it is empty just return null)

MySQL 5.7 date field trouble

I have installed recently MySQL 5.7 . Something weird is happening with a date column.
If I execute a SELECT query using that field in a WHERE section, I have a resultset, but when I use the same WHERE condition to UPDATE a row I get an Invalid date format error message.
Here is the SELECT sentence:
SELECT *
FROM
FDpoCargTran
WHERE FDpoCargTran.Banco = '001'
AND (FDpoCargTran.Conciliacion = '' OR FDpoCargTran.Conciliacion IS NULL)
AND FDpoCargTran.Fecha = '2016-09-27'
This sentence returns 2 rows resultset, that's ok.
Now, Here's the UPDATE sentence:
UPDATE
FDpoCargTran
SET
Edo = 'C'
WHERE FDpoCargTran.Banco = '001'
AND (FDpoCargTran.Conciliacion = '' OR FDpoCargTran.Conciliacion IS NULL)
AND FDpoCargTran.Fecha = '2016-09-27'
AND Deposito = 1041
And I get this error message:
Data truncation: Incorrect date value: '' for column 'Conciliacion'
The Conciliacion columns is defined as:
`Conciliacion` date DEFAULT NULL,
If I remove the Conciliacion = '' condition, everything works fine.
Why empty string is not valid to evaluate the column in an UPDATE sentence and not in a SELECT?
Please, an idea!!!
Basically, for date datatype, you cannot store something like White
Spaces or ' ' strings. You need to make the column to accept NULL
values and insert an actual NULL into it. This is not a problem in MySQL 5.7, its how date is set in databases.
Update is a DML statement, when you actually want to write something into table, or check for a condition, MySQL is unable to understand what ' ' is for the date column type.
So, you cannot have ' ', instead you can have NULL set. Thats how MySQL can check the condition and make appropriate changes!!
I would suggest, change it to NULL.
Alter your datetime column to varchar.
Import whatever table/database.
Update FDpoCargTran set Conciliacion=NULL where Conciliacion='';
Alter column back to datetime.

mySQL str_to_date() function returns error

I keep receiving an error message when trying to convert a column, CreatedDate, of string date values in my Estimates table into the mySQL date format using str_to_date(). My column of data contains dates in m/d/yy format (for example: 1/26/16 or 3/3/16).
I ran this query:
UPDATE Estimates
SET CreatedDate = str_to_date( CreatedDate, '%c/%e/%y' )
mySQL is returning this error message:
Error
SQL query:
UPDATE Estimates
SET CreatedDate = str_to_date( CreatedDate, '%c/%e/%y' )
MySQL said: #1411 - Incorrect datetime value: '' for function str_to_date
What is wrong with my query?
Disable NO_ZERO_DATE SQL mode:
set #old_sql_mode = ##sql_mode;
set sql_mode = '';
Run your statement:
UPDATE Estimates
SET CreatedDate = NULLIF(str_to_date(CreatedDate, '%c/%e/%y'), FROM_DAYS(0))
Then enable original SQL modes:
set sql_mode = #old_sql_mode;
Disabling NO_ZERO_DATE mode will make STR_TO_DATE return zero date 0000-00-00 for invalid date strings, the same value is returned by FROM_DAYS(0). So NULLIF will convert zero dates to NULL.
This answer was helpful.
The usual strategy for cleaning up data like this is as follows:
ALTER TABLE Estimates CHANGE COLUMN CreatedDate CreatedDateString VARCHAR(255);
ALTER TABLE Estimates ADD COLUMN CreatedDate DATE
UPDATE Estimates SET CreatedDate=STR_TO_DATE(CreatedDateString, '%c/%e/%y'))
WHERE CreatedDateString IS NOT NULL AND CreatedDateString != ''
Then when you're confident everything got converted correctly:
ALTER TABLE Estimates DROP COLUMN CreatedDateString
The advantage to proper DATE fields is they're in a consistent format and when you add an INDEX on them data retrieval is very fast, even on ranges, like:
SELECT * FROM Estimates WHERE CreatedDate BETWEEN '2016-01-01' AND '2016-06-30'
It's hitting blank values in your column.
SET CreatedDate = str_to_date( '', '%c/%e/%y' )
I think this outputs 0000-00-00 and that works as an invalid date if you are setting a date field to that.
SET CreatedDate = STR_TO_DATE( IFNULL(case when CreatedDate = '' then null else createddate end,'1901-1-1'), '%c/%e/%y' )
That will leave 1901-01-01 values for nulls and blank
Added to tadman:
SET CreatedDate = STR_TO_DATE(case when CreatedDate = '' then null else createddate end, '%c/%e/%y' )
Nulls instead of 1901-01-01 if you prefer.

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