How to convert NVARCHAR to BIT in mssql - sql-server

I am new to mssql , Here I receive a parameter as "NVARCHAR" but the column datatype is BIT so I need to convert the Nvarchar data as Bit data.
Here the Nvarchar data is always either "True" or "False".
INSERT INTO EC_CUSTOMER_PROFILE(
CP_SEND_NEWS_LETTER,
CP_SEND_PARTNER_SPECIAL_OFFER,
CP_CREATION_DATE,
CP_CREATED_BY)
VALUES(
#mNewsLetter, //Nvarchar(50)
#mSpecialOffer, //Nvarchar(50)
GETDATE(),
#mUserId)
Can anyone help me to fix it .

Just use a CASE expression, e.g.
CASE #mSpecialOffer WHEN 'TRUE' THEN 1 ELSE 0 END
so...
INSERT INTO EC_CUSTOMER_PROFILE(
CP_SEND_NEWS_LETTER,
CP_SEND_PARTNER_SPECIAL_OFFER,
CP_CREATION_DATE,
CP_CREATED_BY)
VALUES(
CASE #mNewsLetter WHEN 'TRUE' THEN 1 ELSE 0 END,
CASE #mSpecialOffer WHEN 'TRUE' THEN 1 ELSE 0 END,
GETDATE(),
#mUserId)

Just cast it as bit.
The strings True and False are interpreted as you would expect.
INSERT INTO EC_CUSTOMER_PROFILE
(CP_SEND_NEWS_LETTER,
CP_SEND_PARTNER_SPECIAL_OFFER,
CP_CREATION_DATE,
CP_CREATED_BY)
VALUES ( CAST(#mNewsLetter AS BIT),CAST(#mSpecialOffer AS BIT),GETDATE(),#mUserId)

INSERT INTO EC_CUSTOMER_PROFILE(
CP_SEND_NEWS_LETTER,
CP_SEND_PARTNER_SPECIAL_OFFER,
CP_CREATION_DATE,
CP_CREATED_BY)
VALUES(
CASE WHEN #mNewsLetter = 'True' THEN 1
WHEN #mNewsLetter = 'False' THEN 0
END,
CASE WHEN #mSpecialOffer = 'True' THEN 1
WHEN #mSpecialOffer = 'False' THEN 0
END,
GETDATE(),
#mUserId)

Related

T-SQL unexpected behavior in isnull function

When i run this query i expect the result will be 'false'
IF isnull(0,'') = ''
select 'true'
else
select 'false'
But sql Server tells me 'true', why?
In this case ISNULL(0,'') returns an integer. SQL Server will cast the second argument to an integer too, ie 0. So 0=0, hence the result is TRUE. Comparing directly to 0 would also return true:
IF 0 = ''
select 'true'
else
select 'false'
Using ISNULL and NULL like this is unusual. An ISNULL(someColumn='') function in a WHERE clause would prevent the optimizer from using any indexes that covered someColumn thus forcing a scan instead of an index seek.
Using IF statements in SELECT is impossible. Even in CASE statements, it's better to explicitly check for NULL than apply such transformations.
For your case, when compare two values, the '' will be converted to int first. The following:
SELECT CONVERT(INT, '')
returns 0, so 0=0 is true
If you want treat 0 as NULL, you can use NULLIF:
DECLARE #i INT = 0
IF NULLIF(ISNULL(#i, ''), 0) = ''
SELECT 'true'
ELSE
SELECT 'false'
This would return 'false'
ISNULL are identical when there are just two values (i.e. NULL and 0) so, it will be true in IF condition and select 'true' will be printed.

SQL Server 2008 Case When Cast

I'm having trouble figuring this statement out. It seems that SQL Server is still executing the THEN part in the CASE WHEN statement. Please see this query.
SELECT
CASE
WHEN ISNUMERIC('INC') = 1
THEN CAST('INC' as numeric(10,2))
ELSE 'FALSE'
END AS foo
SQL Server is returning
"Error converting data type varchar to numeric"
From this query it should return FALSE and not return an Error since the THEN part was not executed.
What is wrong with my query?
The problem is that you are returning two different data types from the same column. So try this one -
DECLARE #value CHAR(3)
SET #value = 66
SELECT
CASE WHEN ISNUMERIC(#value) = 1
THEN CAST(CAST(#value AS NUMERIC(10,2)) AS VARCHAR(30))
ELSE 'FALSE'
END AS foo
That is because, your query is trying to
CAST 'FALSE' as Numeric(10,2)
Try this
SELECT CASE WHEN ISNUMERIC('INC') = 1 THEN
CAST(CAST('INC' as numeric(10,2)) AS varchar(5))
ELSE 'FALSE' END AS foo
The problem is that one branch of you CASE branches returns VARCHAR and the other a number.
Try the following:
CASE WHEN ISNUMERIC('INC') = 1
THEN CAST(CAST('INC' AS NUMERIC(10,2)) AS NVARCHAR)
ELSE 'FALSE'
END AS foo

How to check if bit variable is true or false in sql server?

I have a simple query and all I want to do is check if this variable is true or false, and for some reason it always returns false.
DECLARE #CappedIFCheck BIT
SET #CappedIFCheck = (SELECT distinct 1
FROM mytable
WHERE 1=1);
select #CappedIFCheck
IF (#CappedIFCheck = 'True')
BEGIN
SELECT 'true';
END
ELSE
BEGIN
SELECT 'false';
END
When comparing BIT values in Sql Server, use literal values 1 and 0 instead of 'True' and 'False'.
IF (#CappedIFCheck = 1) ...
A bit variable in SQL Server can have three values. 0, 1 and NULL.
The strings 'true' and 'false' map to 1 and 0 respectively.
Your code does not take account of the third possible value. If mytable is empty then the variable will not be initialised and have the value NULL.
SELECT CASE #CappedIFCheck
WHEN 'True' THEN 'true'
WHEN 'False' THEN 'false'
ELSE 'unknown'
END
I'm not sure exactly what your code is trying to do but that is a very inefficient way of going about things. You should use EXISTS instead.
Try the set clause like this:
SET #CappedIFCheck = ISNULL((select 1 where exists (select 1 from MyTable where 1=0)),0)

determine if any values are null, if true then false, else true

I currently have a select statement that checks several columns to see if they have data. if any of them are null then i want a bit set to false. if none of them are null then i want a bit set to true. here's what i currently have:
select
cast(
case when ChangeOrderNumber is null then 0 else 1 end *
case when ClientName is null then 0 else 1 end *
case when QuoteNumber is null then 0 else 1 end *
case when ClientNumber is null then 0 else 1 end *
case when ServiceLine is null then 0 else 1 end *
case when ServiceLineCode is null then 0 else 1 end *
case when GroupLeader is null then 0 else 1 end *
case when CreatedBy is null then 0 else 1 end *
case when PTWCompletionDate is null then 0 else 1 end *
case when BudgetedHours is null then 0 else 1 end *
case when BudgetDollars is null then 0 else 1 end *
case when InternalDeadlineDate is null then 0 else 1 end *
case when ProjectDescription is null then 0 else 1 end *
case when Sales is null then 0 else 1 end *
case when Coop is null then 0 else 1 end *
case when PassThrough is null then 0 else 1 end *
case when POStatus is null then 0 else 1 end *
case when PONumber is null then 0 else 1 end as bit
)
as Flag
from t
now, that code works, but it's a bit lengthy, i was wondering if anyone knew of a better way to do this. please note that there are several data types being checked.
further details:
this code is in a view that is being looked at in an application for processing change orders. before a change order can be processed it must meet some data quality checks. this view shows if any of the required data is null.
Just add them up since NULL + "something" is always NULL ...
CREATE TABLE #test(column1 int,column2 varchar(4),column3 float)
INSERT #test VALUES(2,'2',2)
INSERT #test VALUES(0,'1',0)
INSERT #test VALUES(null,'1',0)
INSERT #test VALUES(1,null,0)
INSERT #test VALUES(0,'1',null)
INSERT #test VALUES(null,null,null)
SELECT CASE
WHEN column1 + column2 + column3 is NULL THEN 0 ELSE 1 END, *
FROM #test
from a post I created over 3 years ago ...
Keep in mind that if you have characters that are not numbers that you have to convert to varchar ...
INSERT #test VALUES(0,'abc',null)
Here is the conversion, no need to convert the varchar columns
SELECT CASE WHEN CONVERT(VARCHAR(100),column1)
+ column2
+CONVERT(VARCHAR(100),column3) is NULL THEN 0 ELSE 1 END,*
FROM #test
I think I might go with this solution unless someone comes up with a better one, inspired by #Alireza:
cast(
case when (ChangeOrderNumber is null or
a.ClientName is null or
a.QuoteNumber is null or
ClientNumber is null or
ServiceLine is null or
ServiceLineCode is null or
GroupLeader is null or
CreatedBy is null or
PTWCompletionDate is null or
BudgetedHours is null or
BudgetDollars is null or
InternalDeadlineDate is null or
ProjectDescription is null or
Sales is null or
Coop is null or
PassThrough is null or
POStatus is null or
PONumber is null) then 'false' else 'true'
end as bit) as Flag
Please use IIF() (need to be sql server 2012 or later) I really recommend:
IIF(column1 is null, '0', '1')
What about this one?
select not(a is null or b is null or ...)
You could invert the logic.
SELECT
CASE WHEN ChangeOrderNumber IS NOT NULL
AND ClientName IS NOT NULL
AND QuoteNumber IS NOT NULL
....
THEN 1
ELSE 0
END [Flag]
FROM t
Create a HasValue function that takes in a sql_variant and returns a bit. Then use bitwise AND in your SELECT clause.
CREATE FUNCTION dbo.HasValue(#value sql_variant) RETURNS bit
AS
BEGIN
RETURN (SELECT COUNT(#value))
END
GO
SELECT dbo.HasValue(ChangeOrderNumber)
& dbo.HasValue(ClientName)
& dbo.HasValue(QuoteNumber)
...
as [Flag]
FROM t
Or this:
declare #test1 char(1)
declare #test2 char(1)
declare #outbit bit
set #test1 = NULL
set #test2 = 'some value'
set #outbit = 'True'
select #test1
select #test2
If #test1 + #test2 IS NULL set #outbit = 'False'
Select #outbit
Much simpler -- just use the COALESCE function, which returns the value in the first non-null column.
SELECT Flag = CASE
WHEN COALESCE (column1, column2, column3, ...) IS NULL THEN 0
ELSE 1
END
FROM MyTable

Is it possible to convert nvarchar to int?

I have tried something like this:
select PREPRO = case when (isnumeric(PREPRO) = 1 and
PREPRO in ('0','1','-1')) or
convert(varchar, PREPRO) in ('True','False')
then convert(bit, convert(integer, PREPRO)) else 'No' end
from dbo.TI10SE
The PREPRO contains all "False".
I get this error:
Conversion failed when converting the nvarchar value 'False' to data type int.
Does it mean that an nvarchar can not be converted to an integer ever? I guess its because some data may be lost.
You are trying to convert your PREPRO to an integer, even if the value it holds is True or False:
convert(integer, PREPRO)
You cannot convert the value False to an integer.
The conditional in your when clause evaluates to true when PREPRO is a number within 0, 1, -1 OR when it evaluates to either True or False. In any of these cases, you attempt to convert this value to an integer and then to a bit.
Use CASE to accomplish this:
DECLARE #PREPRO VARCHAR(5)
SET #PREPRO = 'False'
SELECT CASE WHEN #PREPRO = 'False' THEN 0 ELSE 1 END
nvarchar can be converted to an integer if it contains an integer
DECLARE #PREPRO VARCHAR(5)
SET #PREPRO = '10'
SELECT CONVERT(integer, #PREPRO)
T-SQL doesn't know what to associate with 'False' or 'True', so you will have to use a CASE statement like rdkleine said.
Also in this statement:
convert(bit, convert(integer, PREPRO)) else 'No' end
You're going to receive an error, because 'No' is not of type bit, what are you trying to return?

Resources