How to select BIT columns as TRUE - sql

I have a table called TP_Roles.
This Table structure is:
Id PK, int, not null
Role_Name varchar(200), null
IsActive bit, null
How Do I insert bit value as True instead of 1 ?
Many thanks.

BIT values are 1/0 and they correspond to TRUE/FALSE accordingly.
By the comments I assume you want to view TRUE / FALSE when selecting this column, so you can simply use a CASE EXPRESSION for this:
SELECT <Column1>,<Column2>...,
CASE WHEN IsActive = 1 THEN 'TRUE' ELSE 'FALSE' END as IsActive
FROM YourTable
If IsActive = 1 - display TRUE , else , display FALSE.

Related

How to set bool value in SQL

I have a column which is bool. How can I set true, false values for that? Here is my query :
Update [mydb].[dbo].[myTable]
SET isTrue =
(
CASE WHEN Name = 'Jason' THEN 1
END
)
I don't know what to write after THEN keyword. Should I write 1 or true or 1 AS BIT or something else?
Sql server does not expose a boolean data type which can be used in queries.
Instead, it has a bit data type where the possible values are 0 or 1.
So to answer your question, you should use 1 to indicate a true value, 0 to indicate a false value, or null to indicate an unknown value.
Update [mydb].[dbo].[myTable]
SET isTrue =
CASE WHEN Name = 'Jason' THEN
1
ELSE
0
END
The query you added will work fine, but it will you have to take care of "FALSE" part as well otherwise it will try to enter NULL in your column.
Do you have any default value constrain on isTrue column?
Update [mydb].[dbo].[myTable]
SET isTrue =
(
CASE WHEN Name = 'Jason' THEN 1 ELSE 0
END
)
You need case statement with when and else if not any condition satisfied
Update [mydb].[dbo].[myTable]
SET isTrue = ( CASE WHEN Name = 'Jason'
THEN 1 else 0
END)
Use IIF function of sql server
DECLARE #a int = 45, #b int = 40;
DECLARE #a int = 45, #b int = 40;
SELECT IIF ( #a > #b, 'TRUE', 'FALSE' ) AS Result;
Result
--------
TRUE
(1 row(s) affected)
For Your Problem
Update [mydb].[dbo].[myTable]
SET isTrue = ( Name = 'Jason', 'TRUE', 'FALSE' )

How to update the data based on column which has bit data type in T-SQL

Test Table with 3 columns (FirstName, LastName, Status)
I want to update first names and last names of all rows in a single UPDATE query for any status either it is true or false. How do I write this?
The SQL Server bit data type stores 1/0 for true/false values, and will convert the strings 'true' and 'false' to 1 and 0 respectively. Thus you can query based on '0' or '1', or 'False' or 'True'
If you want logic to update all rows with a single update query, and have a different update depending on the value of [Status] column, then you need a case statement:
There are multiple ways to do this, some examples of which can be seen in the example and results below:
-- Let's make a test table that mimicks your schema and put some data in it
-- We will use a function to re-make the table
Create Function MakeTestTable ()
Returns #Test Table (
FirstName varchar(50),
LastName varchar(50),
[Status] bit
)
As Begin
Insert Into #Test Values
('John', 'Doe', 'false'),
('Jane', 'Dane', 'true'),
('Space', 'Cadet', Null)
Return
End
Go
-- Our local test table variable for examples:
Declare #Test Table (
FirstName varchar(50),
LastName varchar(50),
[Status] bit
)
-- Let's seed the test table
Insert Into #Test Select * From MakeTestTable()
-- Verify initial Values
Select * From #Test
-- Single update statement depending on [Status] value using Case statement:
Update #Test
Set FirstName =
Case -- Here we use 1/0 for True/False, respectively
When [Status] = 1 Then 'FirstName updated while Status was True'
When [Status] = 0 Then 'FirstName updated while Status was False'
Else 'FirstName updated while Status was Null'
End,
LastName =
Case -- Here we use 'True' and 'False' which SQL converts to 1 and 0, respectively
When [Status] = 'True' Then 'LastName updated while Status was True'
When [Status] = 'False' Then 'LastName updated while Status was False'
Else 'LastName updated while Status was Null'
End
-- Verify our updates:
Select * From #Test
-- Reset for next example:
Delete #Test; Insert Into #Test Select * From MakeTestTable()
-- Single update statement based on [Status] value not being null using Case statement:
Update #Test
Set FirstName =
Case -- Here we update if the value of [Status] is either 0 or 1 using In clause
When [Status] In (0,1) Then 'FirstName updated while Status was True or False'
Else 'FirstName updated while Status was neither 0 nor 1'
End,
LastName =
Case -- Here we base our update on [Status] being null (reverse of the above)
When [Status] Is Not Null Then 'LastName updated while Status was Not Null'
Else 'LastName updated while Status was Null'
End
-- Verify our updates:
Select * From #Test
-- Reset for next example:
Delete #Test; Insert Into #Test Select * From MakeTestTable()
-- Finally, update all columns based on status not being null using Where clause:
-- Without the CASE statement, the WHERE clause is applied to the entire update,
-- The code is simpler, but you lose the ability to update each column based on a
-- different condition.
Update #Test
Set FirstName = 'FirstName updated while Status is not Null',
LastName = 'LastName updated while Status is not Null'
Where [Status] Is Not Null
-- Verify our updates:
Select * From #Test
-- Clean up
Drop Function MakeTestTable
If Status does not allow null then every row is true or false
update table set firstname = 'fname';
If Status does allow null then
update table set firstname = 'fname' where status is not null;
if you have different updates for different values then just use two updates
update table set firstname = 'fnameT' where status = 'true';
update table set firstname = 'fnameF' where status = 'false';

how to get "AND" of all the values of a boolean column in a single sql

how to get "AND" of all the values of a boolean column in a single sql query.
for above the o/p should be false,
if all were true then o/p: true,
if all/atlease one value false , then o/p: false.
Try this
IF EXISTS (SELECT ActiveStatus From TableName where ActiveStatus = 0)
SELECT 'False'
ELSE
SELECT 'True'
AS OutputColumn
You can indirectly use MIN for AND, and MAX for OR.if you take into account that a BIT colum is either zero or one:
MIN: only if all the values are 1 (true) the result will be 1 (true), it works like AND
MAX: if there is at least a 1 (true) the result will be 1 (true), it works like OR
If you try to use MIN or MAX directly on a BIT column, it will fail, so you need to cast it to an integer type, and back to bit, like this:
SELECT CAST(MIN(CAST(BitColumn AS TINYINT)) AS BIT) FROM Table -- for AND
SELECT CAST(MAX(CAST(Bitcolumn AS TINYINT)) AS BIT) FROM Table -- for OR
It's easy to include this in a more complex query, for example one with GROUP BY
declare #status varchar(10)
if exists(select null from [Status] where ActiveStatus = 0)
set #status = 'false'
else
set #status = 'true'
select #status as [Status]

Return Value Column Name

The stored procedure below works correctly as expected. Returning True if "FleetBarcode" exists and False if it doesn't.
However, when it returns it it displays it as below
(no column name)
True
My problem is I need the "No Column Name" part to have a defined column name. Tried the method below so far which gives the 'True' field an alias.
Thank you for your time.
ALTER proc [dbo].[usp_getjobs]
#barcode as nvarchar(20)
as
SELECT CASE WHEN EXISTS(
SELECT
[FleetBarcode],
[Deleted]
FROM w_DeliveryItems
WHERE FleetBarcode = #barcode
AND Deleted != 1
)
THEN (SELECT 'True' 'Exist')
ELSE (SELECT 'False' 'Exist')
END
Use
ALTER PROC [dbo].[usp_getjobs] #barcode AS NVARCHAR(20)
AS
SELECT CASE
WHEN EXISTS(SELECT [FleetBarcode],
[Deleted]
FROM w_DeliveryItems
WHERE FleetBarcode = #barcode
AND Deleted != 1) THEN 'True'
ELSE 'False'
END AS [Exist]
The alias needs to go on the outer SELECT.
Also for column aliasing it is more common to use square brackets than single quotes.
Get rid if the SELECTs in the THEN/ELSE blocks and use AS to give the column a name:
SELECT CASE WHEN EXISTS(
...
THEN 'True')
ELSE 'False')
END AS [Exist] --<-- add name here
ALTER proc [dbo].[usp_getjobs]
#barcode as nvarchar(20)
as
SELECT CASE WHEN EXISTS(
SELECT
[FleetBarcode],
[Deleted]
FROM w_DeliveryItems
WHERE FleetBarcode = #barcode
AND Deleted != 1
)
THEN (SELECT 'True' 'Exist')
ELSE (SELECT 'False' 'Exist')
END AS [Your Column Name]

Using Case Statement in SQL with parameter/variable to check for Null values

I am trying to write a SQL Select statement to return records based on a user input through a front end.
I want to write the Select statement like this:
SELECT somefields
FROM sometable
WHERE CASE variable
WHEN 'blank' THEN field IS NULL
ELSE field = field
END
Basically I either want to filter a column to find NULL values or ignore the filter and return all values depending on the value of the variable. I know that the results of the CASE statement is not executable but how can I do this?
When variable is 'blank', the following query will give you rows where field is NULL. When variable is anything else, it will give you all rows:
SELECT somefields
FROM sometable
WHERE
(variable = 'blank' AND field IS NULL)
OR (variable <> 'blank')
You can use NULLIF() (link is for SQL Server, but NULLIF() should be standard):
SELECT somefields
FROM sometable
WHERE field = NULLIF(variable, 'blank')
The following snippet should behave as follows:
when #variable is null, return all rows
when #variable = 'blank', return all rows where field is null or field = 'blank'
otherwise, return rows where #variable equals field
Code snippet:
WHERE 1 = CASE
WHEN #variable is null then 1
WHEN #variable = 'blank' and field is null then 1
WHEN #variable = field then 1
END
SELECT somefields
FROM sometable
WHERE ((variable IS NULL OR variable = 0) OR (variable = field))
WHERE Criteria is apply when variable have value
For Example:
DECLARE #CityName VARCHAR(50)
SET #CityName = NULL
SELECT CityName
FROM City
WHERE ((#CityName IS NULL ) OR (#CityName = CityName ))
When City is null then tables return all rows
I think I get what you're after. Something like this maybe?
SELECT field1,
field2,
CASE variable
WHEN 'blank' THEN NULL
ELSE field3
END as field3
FROM sometable
Think I understand what you mean....for example....
SELECT
House, Postcode
from
SomeTable
where
(House=isnull(#House,House) or (House is null and #House is null))
and
(Postcode=isnull(#Postcode,Postcode) or (Postcode is null and #Postcode is null))
First bit of the conditional where is to use the variable, when present (the isnull bit is to ignore the variable if it's null)
Second bit of the conditional where is in case your evaluative field is null also as effectively fields don't = null they are 'is null'.
Confused? Good. Works on what I'm doing though!
Here is my solution based on #Andomar answer above aimed at anyone testing an input varchar value, you need to test the parameter in the right order as per the example below:
FIELD1 = CASE
WHEN #inputParameter = '' THEN FIELD1
WHEN #inputParameter <> FIELD1 THEN NULL -- if input is some text but does not match
WHEN #inputParameter IS NULL THEN FIELD1
WHEN #inputParameter != '' AND FIELD1 = #inputParameter THEN FIELD1
END
Hope this helps someone.