Update column using case expression sql - sql

I want to set column value only if it is not blank.
Here is sample
Declare #Temp Varchar(20)
Update Logins
Set ColValue =
Case When #Temp <> '' Then #Temp Else /* Dont SET Value */ End
Where Code=1
What to write in Else Part ?
I have multiple columns to update and want to apply condition in only single column
DB : SQL SERVER 2008

You have to set the updated column as below:
Declare #Temp Varchar(20)
Update Logins
Set ColValue = Case When #Temp <> '' Then #Temp
Else ColValue
End
Where Code=1

You can check your variable in WHERE to not update at all when it's blank
Declare #Temp Varchar(20)
Update Logins
Set ColValue = #Temp
Where Code=1 AND #Temp <> ''

Related

There is already an object named '#BaseData' in the database

Below is a snippet of my code.
I am wanting to filter my data based upon a variable.
When I try to run the code, it returns an error of "There is already an object named '#BaseData' in the database.". I am not sure as to why this is the case; I have put extra checks within the IF statements to drop the temp table if it already exists but to no avail.
Are you able to help or provide an alternative solution please?
DECLARE #Variable AS VARCHAR(20) = 'Example1'
IF OBJECT_ID(N'TEMPDB..#BaseData') IS NOT NULL
DROP TABLE #BaseData
IF #Variable = 'Example1'
BEGIN
SELECT
*
INTO
#BaseData
FROM
[Database].[schema].[table]
END
IF #Variable = 'Example2'
BEGIN
SELECT
*
INTO
#BaseData
FROM
[Database].[schema].[table]
WHERE
[column] = 1
END
IF #Variable = 'Example3'
BEGIN
SELECT
*
INTO
#BaseData
FROM
[Database].[schema].[table]
WHERE
[column] = 0
END
While code is compiled by SQL, creation of same #table is found in each condition so it doesn't work.
One possible solution would be to create table and than insert data conditionally.
-- DROP TEMP TABLE IF EXISTS
IF OBJECT_ID(N'TEMPDB..#BaseData') IS NOT NULL
DROP TABLE #BaseData
GO
-- CRATE TEMP TABLE WITH TempId, AND SAME STRUCTURE AS YOUR TABLE
SELECT TOP 0 CONVERT(INT, 0)TempId, * INTO #BaseData FROM TestTable
-- DECLARE VARIABLE
DECLARE #Variable AS VARCHAR(20)= 'Example1'
-- INSERT DATA IN TABLE DEPENDING FROM CONDITION
IF (#Variable = 'Example1')
BEGIN
INSERT INTO #BaseData SELECT * FROM TestTable
END
IF (#Variable = 'Example2')
BEGIN
INSERT INTO #BaseData SELECT * FROM TestTable WHERE Id = 1
END
IF (#Variable = 'Example3')
BEGIN
INSERT INTO #BaseData SELECT * FROM TestTable WHERE Id = 2
END

Show other column value if the value of the column is NULL or blank

I want to display value of other column if the value of my column is NULL or blank. Below is my table.
DECLARE #Tab TABLE(ID INT, suser VARCHAR(10), sgroup VARCHAR(10), sregion VARCHAR(10))
INSERT INTO #Tab VALUES(1,'Test',NULL,NULL),(2,'','Group',NULL),(3,NULL,NULL,'Region'),(4,NULL,NULL,NULL)
SELECT * from #Tab
My Query:
SELECT ID
,Case WHEN suser IS NULL OR suser = ''
THEN sgroup
WHEN sgroup IS NULL OR sgroup = ''
THEN sregion
ELSE NULL
END AS col
from #Tab
I want oupput as:-
DECLARE #Tab1 TABLE(ID INT, col VARCHAR(10))
INSERT INTO #Tab1 VALUES(1,'Test'),(2,'Group'),(3,'Region'),(4,NULL)
SELECT * from #Tab1
Thanks
Blank and NULL are not the same. If you want to treat '' and NULL as the same value, one method would be to use NULLIF:
ISNULL(NULLIF(YourFirstColumn,''),YourOtherColumn)
Ideally, however, if either could be stored in your data but they should be treated as the same, don't allow one of them. Personally, I would update all the values of the column to NULL where they have a value of '' and then add a constraint that doesn't allow the value ''. Something like:
UPDATE YourTable
SET YourColumn = NULL
WHERE YourColumn = '';
ALTER TABLE YourTable ADD CONSTRAINT YourColumn_NotBlank CHECK (YourColumn IS NULL OR YourColumn <> '');
use COALESCE function it will return 1st non null value
SELECT ID ,COALESCE(suser , sgroup, sregion)
col
from #Tab

Split column value to match yes or no

I have two tables named Retail and Activity and the data is as shown below:
Retail Table
Activity Table
My main concern is about Ok and Fault column of the table Retail, as you can see it contains comma separated value of ActivityId.
What i want is, if the Ok column has ActivityId the corresponding column will have Yes, if the Fault column has ActivityId then it should be marked as No
Note I have only four columns that is fixed, it means i have to check that either four of the columns has its value in Ok or Fault, if yes then only i have to print yes or no, otherwise null.
Desired result should be like :
If the value is in Ok then yes other wise No.
I guessing you want to store 'yes' or 'No' in some column. Below is the query to update that column :
UPDATE RetailTable
SET <Result_Column>=
CASE
WHEN Ok IS NOT NULL THEN 'Yes'
WHEN Fault IS NOT NULL THEN 'No'
END
You can use below code as staring point:
DECLARE #Retail TABLE
(
PhoneAuditID INT,
HandsetQuoteID INT,
Ok VARCHAR(50)
)
INSERT INTO #Retail VALUES (1, 1009228, '4,22,5')
INSERT INTO #Retail VALUES (2, 1009229, '1')
DECLARE #Activity TABLE
(
ID INT,
Activity VARCHAR(50)
)
INSERT INTO #Activity VALUES (1, 'BatteryOK?'), (4, 'PhonePowersUp?'), (22,'SomeOtherQuestion?'), (5,'LCD works OK?')
SELECT R.[PhoneAuditID], R.[HandsetQuoteID], A.[Activity], [Ok] = CASE WHEN A.[ID] IS NOT NULL THEN 'Yes' END
FROM #Retail R
CROSS APPLY dbo.Split(R.Ok, ',') S
LEFT JOIN #Activity A ON S.[items] = A.[ID]
I have used Split function provided here:
separate comma separated values and store in table in sql server
Try following query. i have used pivot to show row as columns. I have also used split function to split id values which you can find easily on net:
CREATE TABLE PhoneAudit
(
PhoneAuditRetailID INT,
HandsetQuoteID INT,
Ok VARCHAR(50),
Fault VARCHAR(50)
)
INSERT INTO PhoneAudit VALUES (1,10090,'1,2','3')
CREATE TABLE ActivityT
(
ID INT,
Activity VARCHAR(100)
)
INSERT INTO ActivityT VALUES (1,'Battery')
INSERT INTO ActivityT VALUES (2,'HasCharger')
INSERT INTO ActivityT VALUES (3,'HasMemoryCard')
INSERT INTO ActivityT VALUES (4,'Test')
DECLARE #SQL AS NVARCHAR(MAX)
DECLARE #ColumnName AS NVARCHAR(MAX)
SELECT #ColumnName= ISNULL(#ColumnName + ',','') + QUOTENAME(Activity) FROM (SELECT DISTINCT Activity FROM ActivityT) AS Activities
SET #SQL = 'SELECT PhoneAuditRetailID, HandsetQuoteID,
' + #ColumnName + '
FROM
(SELECT
t1.PhoneAuditRetailID,
t1.HandsetQuoteID,
TEMPOK.*
FROM
PhoneAudit t1
CROSS APPLY
(
SELECT
Activity,
(CASE WHEN ID IN (SELECT * FROM dbo.SplitIDs(t1.Ok,'',''))
THEN ''YES''
ELSE ''NO''
END) AS VALUE
FROM
ActivityT t2
) AS TEMPOK) AS t3
PIVOT
(
MIN(VALUE)
FOR Activity IN ('+ #ColumnName + ')
) AS PivotTable;'
EXEC sp_executesql #SQL
DROP TABLE PhoneAudit
DROP TABLE ActivityT
There are several ways to do this. If you are looking for a purely declarative approach, you could use a recursive CTE. The following example of this is presented as a generic solution with test data which should be adaptable to your needs:
Declare #Delimiter As Varchar(2)
Set #Delimiter = ','
Declare #Strings As Table
(
String Varchar(50)
)
Insert Into #Strings
Values
('12,345,6,78,9'),
(Null),
(''),
('123')
;With String_Columns As
(
Select
String,
Case
When String Is Null Then ''
When CharIndex(#Delimiter,String,0) = 0 Then ''
When Len(String) = 0 Then ''
Else Left(String,CharIndex(#Delimiter,String,0)-1)
End As String_Column,
Case
When String Is Null Then ''
When CharIndex(#Delimiter,String,0) = 0 Then ''
When Len(String) = 0 Then ''
When Len(Left(String,CharIndex(#Delimiter,String,0)-1)) = 0 Then ''
Else Right(String,Len(String)-Len(Left(String,CharIndex(#Delimiter,String,0)-1))-1)
End As Remainder,
1 As String_Column_Number
From
#Strings
Union All
Select
String,
Case
When CharIndex(#Delimiter,Remainder,0) = 0 Then Remainder
Else Left(Remainder,CharIndex(#Delimiter,Remainder,0)-1)
End As Remainder,
Case
When CharIndex(#Delimiter,Remainder,0) = 0 Then ''
When Len(Left(Remainder,CharIndex(#Delimiter,Remainder,0)-1)) = 0 Then ''
Else Right(Remainder,Len(Remainder)-Len(Left(Remainder,CharIndex(#Delimiter,Remainder,0)-1))-1)
End As Remainder,
String_Column_Number + 1
From
String_Columns
Where
(Remainder Is Not Null And Len(Remainder) > 1)
)
Select
String,
String_Column,
String_Column_Number
From
String_Columns

Why column_a += #value is not equal to column_a = column_a + #value in SQL Server 2008?

I wrote a stored procedure to update data in a table. It looks like this:
UPDATE dbo.sample
SET column_a += #value
WHERE id = #id
What I found is it update without sum first. The result is like below command:
UPDATE dbo.sample
SET column_a = #value
WHERE id = #id
I have to use SET column_a = column_a + #value to make it update properly. I want to know why SQL Server does not sum the expression on the right before assign to the left. I tested with variables and it works. It does not work only in this case.
The command that I use right now is:
UPDATE dbo.sample
SET column_a = column_a + #value
WHERE id = #id
I tried the following script. It is working fine for me.
I suggest you to try this once. let me know if the problem still persists.
create table #temp1(id int, prodName varchar(max))
insert into #temp1 values(1,'a')
insert into #temp1 values(2,'b')
insert into #temp1 values(3,'c')
insert into #temp1 values(4,'d')
select * from #temp1
declare #var varchar(1);
set #var = '5'; --note that i even tried declaring it as a varchar. it still works!
update #temp1
set id +=#var
select * from #temp1
drop table #temp1
column_a += #value is equal to column_a = column_a + #value in SQL Server 2008
its just the first one is short

How to Compare two strings using a if in a stored procedure in sql server 2008?

I want to do something like this:
declare #temp as varchar
set #temp='Measure'
if(#temp == 'Measure')
Select Measure from Measuretable
else
Select OtherMeasure from Measuretable
Two things:
Only need one (1) equals sign to evaluate
You need to specify a length on the VARCHAR - the default is a single character.
Use:
DECLARE #temp VARCHAR(10)
SET #temp = 'm'
IF #temp = 'm'
SELECT 'yes'
ELSE
SELECT 'no'
VARCHAR(10) means the VARCHAR will accommodate up to 10 characters. More examples of the behavior -
DECLARE #temp VARCHAR
SET #temp = 'm'
IF #temp = 'm'
SELECT 'yes'
ELSE
SELECT 'no'
...will return "yes"
DECLARE #temp VARCHAR
SET #temp = 'mtest'
IF #temp = 'm'
SELECT 'yes'
ELSE
SELECT 'no'
...will return "no".
You can also try this for match string.
DECLARE #temp1 VARCHAR(1000)
SET #temp1 = '<li>Error in connecting server.</li>'
DECLARE #temp2 VARCHAR(1000)
SET #temp2 = '<li>Error in connecting server. connection timeout.</li>'
IF #temp1 like '%Error in connecting server.%' OR #temp1 like '%Error in connecting server. connection timeout.%'
SELECT 'yes'
ELSE
SELECT 'no'
declare #temp as varchar
set #temp='Measure'
if(#temp = 'Measure')
Select Measure from Measuretable
else
Select OtherMeasure from Measuretable
What you want is a SQL case statement.
The form of these is either:
select case [expression or column]
when [value] then [result]
when [value2] then [result2]
else [value3] end
or:
select case
when [expression or column] = [value] then [result]
when [expression or column] = [value2] then [result2]
else [value3] end
In your example you are after:
declare #temp as varchar(100)
set #temp='Measure'
select case #temp
when 'Measure' then Measure
else OtherMeasure end
from Measuretable