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

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]

Related

How to select from table MariDB

I need to get value from specific data in my_table in MariaDB and store it into variables #var1 and #var2.
In SQL Server I use :
Select #var1=field1 ,#var2=field2 from my_table where id=#varid...
What is the correct syntax for MariaDB or My SQL?
The equal sign compares left and right value and returns 1 (true)/0 (false) or NULL if one of the values is NULL.
To assign a value to a variable use :=:
SELECT #var1:=field1 ,#var2:=field2 from my_table where id=#varid

Is there a function in MySQL to not allow the selection of a value directly after a value already selected from an ENUM data type in the database?

Is there code to not allow a value directly after a value that's already saved be inserted into the table. The field is an ENUM.
Cant find code anywhere
None available for ENUM
Timeslot ENUM('09:00','09:30','10:00')
09:00 saved already
'09:30' shouldn't be allowed to be inserted into the table
'10:00' should insert fine
There is no default function that I am aware of to do what you are wanting.
I think you will have to do some checks using the ENUM index. ENUM values are mapped to a numeric index. You can select column_name+0 on an ENUM column and that will give you the index value of the ENUM rather than the ENUM value. MySQL ENUM Doc
In your case the ENUM index would look something like this:
NULL -> NULL
0 -> ''
1 -> '9:00'
2 -> '9:30'
3 -> '10:00'
For instance, if you have 1 record with Timeslot set to '9:00' and you 'SELECT TimeSlot+0 FROM table' your result for the record will be 1. If the column value was '9:30' the index would be 2, etc.
You can find the potential index of an incoming value using something like this:
SELECT FIND_IN_SET('new_value', REPLACE(SUBSTRING(column_type,6, LENGTH(column_type) - 6), '\'', '') ) AS enum_options
FROM information_schema.columns
WHERE column_name='your_enum_column'
AND table_schema = 'your_schema';
If the result of this is equal to any of the index values (or index value +1) of any of the values already in the table, you do not want to allow this new entry. You can use the above query as a subquery inside a case statement to compare this new value's index to your previous values' indexes.
EDIT (4/2/2019):
After a couple of comments I think that the following may get you closer to what you need. I have not been able to test this query out, but it should be close.
CREATE TEMPORARY TABLE booking_conflicts AS (
SELECT MAX(
IF(
FIND_IN_SET(
(SELECT FIND_IN_SET('12:00', REPLACE(SUBSTRING(column_type,6, LENGTH(column_type) - 6), '\'', '') )
FROM information_schema.columns
WHERE column_name='your_enum_column'
AND table_name = 'booking'
AND table_schema = 'your_schema'),
CONCAT(time_slot+0, ',', time_slot+1)
) > 0,
1,
0) AS is_time_conflict
FROM booking
WHERE facility_id = 6
AND booking_date = '2020-07-04'
);
INSERT INTO bookings
(facility_id,booking_date,time_slot,member_id)
VALUES (6,'2020-07-04','12:00',2)
WHERE (SELECT is_time_conflict FROM booking_conflicts) = 0;
What this is doing is getting all used time_slots from that date for that facility and comparing them with the new time slot you are trying to use. If the new time slot's index is equal to the index of a previously used time_slot or of a previously used time_slot + 1, then the query will return 1, otherwise 0. We store that in a temp table and access the temp table from the insert.

Conditional data type conversion | SQL Server

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.

SQL Update statement truncated incorrect double value error

I'm trying to update my table column values into a string. My query goes like this
UPDATE tbl_testing
SET result= 'Hey'
WHERE (SELECT (colOne) + '-' + (colTwo) + '-' + (colThree)) = 'r-r-r'
which the columns 'colOne, colTwo and colThree' already contains 'r' but slqyog shows "Truncated incorrect DOUBLE value: 'r-r-r'"
and all of the other result column data became = 'Hey'. What should I do?
You have to decide it is either MySQL or MSSQL.
In MySQL the string concatenation is not + sign, but simply you enumerate the columns separated by comma and the statement is SELECT CONCAT("Field1", "Field2" etc) AS ConcatenatedString); - CONCAT() function.
Try reevaluate your DB engine and adapt the query.
In MSSQL the string concatenation is indeed + sign. Your query works ok in MSSQL and updates the result column with the value you have set.
DDL
CREATE TABLE [dbo].[tbl_testing](
[id] [int] NULL,
[result] [nvarchar](4000) NULL,
[colOne] [nvarchar](4000) NULL,
[colTwo] [nvarchar](4000) NULL,
[colThree] [nvarchar](4000) NULL
) ON [PRIMARY]
GO
INSERT INTO tbl_testing (id, colOne, colTwo, colThree)
VALUES (1, 'r', 'r', 'r')
Update statement
UPDATE tbl_testing
SET result='Hey. I am a concatenated string'
WHERE (SELECT (colOne)+'-'+(colTwo)+'-'+(colThree))='r-r-r'
Output
id result colOne colTwo colThree
1 Hey. I am a concatenated string r r r
Changing comment to answer:
You should avoid doing that statements in that way. By doing that, database use no indexes and also you are giving more computation tasks to database server (server needs to concatenate all values and after concatenations will compare with given string).
Better way is to replace yours where statement with something like:
`WHERE colOne = 'r' AND colTwo = 'r' AND ...`
that will work faster without additional computation need (to concatenate strings).
This solution works much much faster, and looks much much better.

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