SQL server trigger concat - sql

I'm trying to write a SQL Server trigger that concats 3 columns, but inserts a string in place of the third column based on a condition.
For example when col 1 is inserted concat col 1, col 2 and col 3. But when col 3 = 'DR' concat Drive or col 3 = 'ST' concat Street etc.
I can write the trigger for all 3 columns, but having trouble with the conditional.
CREATE TRIGGER updateAddress
ON [ARCHIVENEW].dbo.a11
AFTER UPDATE
AS BEGIN
SET NOCOUNT ON;
IF UPDATE(STRNAME)
SELECT CASE
WHEN a11.STRTYPE = 'DR' THEN dbo.a11.STRFNAME = cast(dbo.a11.STRADDLF as varchar(2)) + ' ' + STRNAME + ' ' + 'Drive'
WHEN a11.STRTYPE = 'RP' THEN dbo.a11.STRFNAME = cast(dbo.a11.STRADDLF as varchar(2)) + ' ' + STRNAME + ' ' + 'Ramp'
WHEN a11.STRTYPE = 'EX' THEN dbo.a11.STRFNAME = cast(dbo.a11.STRADDLF as varchar(2)) + ' ' + dbo.a11.STRNAME + ' ' + 'Express Way'
ELSE dbo.a11.STRFNAME = cast(dbo.a11.STRADDLF as varchar(2)) + ' ' + dbo.a11.STRNAME
END
Sorry it took a few days to get back to this and add the code sample. I'm getting a syntax error near the '=' where I try and set my STRFNAME to the concatenated string. To clarify further, col1 is "1234" col2 is "Main" and col3 is "ST". When a row is inserted I'd like col4 to say "1234 Main Street".

Sample table:
CREATE TABLE dbo.TestTable(
Id INT IDENTITY(1,1) PRIMARY KEY
ColA VARCHAR(50),
ColB VARCHAR(50),
ColC VARCHAR(50),
ColD VARCHAR(50)
);
This trigger concats values of ColA, ColB for ColC and validates ColB value for ColD.
CREATE TRIGGER TestTable_UpdateTwoColumns
ON dbo.TestTable
AFTER INSERT,UPDATE
AS
BEGIN
SET NOCOUNT ON;
IF UPDATE(ColA)
BEGIN
UPDATE dbo.TestTable
SET ColC=new.ColA + new.ColB
FROM INSERTED new
END
IF UPDATE(ColB)
BEGIN
UPDATE dbo.TestTable
SET ColD=CASE new.ColB WHEN 'DR' THEN 'Drive' WHEN 'ST' THEN
'Street' END
FROM INSERTED new
END
END
Thanks,

You cannot change a table while the INSERT trigger is firing. You can, however, create a trigger before inserting the record.
CREATE TRIGGER emplog_update AFTER UPDATE ON emp
FOR EACH ROW
INSERT INTO emplog (id, lastnmae, firstname, . . .)
select NEW.id,NEW.lastname,NEW.firstname,NEW.gender,NEW.dob,NEW.marital,NEW.SSN,'U',NULL,USER(),
concat_ws(',',
(case when new.id <> old.id then 'id' end),
(case when new.lastname <> old.lastname then 'lastname' end),
(case when new.firstname <> old.firstname then 'firstname' end),
. . .
);

If your motto is insert into third column, good to use computed column. Here is an example. But as in my comment on question, I did not understand, how col3 value comes?
For this, I used col4 to get the proper result, also in computed column define, it not take reference of own.
CREATE TABLE dbo.Products
(
ProductID int IDENTITY (1,1) NOT NULL
, col1 varchar(50)
, col2 varchar(50)
, col3 varchar(50)
, col4 AS case col3 when 'DR' then 'Drive' when 'ST' then 'Street' else col1 + col2 end
--while computed column define, you can use all other column, except own.
);
-- Insert values into the table.
INSERT INTO dbo.Products (col1, col2,col3)
VALUES ('a', 'a1','a2'), ('b', 'b1', 'DR'), ('c', 'c1', 'ST'), ('d', 'd1', 'd2');
-- Display the rows in the table.
SELECT ProductID, col1, col2, col3, col4
FROM dbo.Products;
select * from products
drop table products

Related

SQL statement with CASE WHEN in ORDER BY causes type convert error

Executing the following code triggers an error:
System.Data.SqlClient.SqlException: 'Cannot convert a char value to money. The char value has incorrect syntax.
All was fine until I have added the second parameter used for sorting purposes.
The code is simplification for clarity.
query as String = "
SELECT a, b, c
FROM DataTable
WHERE c = #PARAM
ORDER BY
CASE #SORTCOLUMN
WHEN 1 THEN a
WHEN 2 THEN b
WHEN 3 THEN c
END"
Dim param As String = "myprarameter"
Dim sortcolumn as Integer = 1
result = connection.Query(Of MyType)(query, New With {Key .PARAM = param, Key .SORTCOLUMN = sortcolumn})
UPDATE:
After hours spent on testing I have narrowed it down to purely SQL issue, not Dapper nor .NET Framework.
Here are my findings:
All works fine until all columns used within CASE WHEN are of the same type (or types and even values which can be easily converted into each other). Once types of columns are different and values cannot be converted, it returns type conversion error. Seems it is trying to convert type of the column selected by CASE WHEN to the type of the first WHENcolumn.
Herewith two examples. I have removed variables for simplicity.
This works:
CREATE TABLE #TestTable1
(col1 money, col2 money)
INSERT INTO #TestTable1
(col1, col2)
VALUES
(1, 30),
(2, 20),
(3, 10)
SELECT col1, col2
FROM #TestTable1
ORDER BY
CASE 2
WHEN 1 THEN col1
WHEN 2 THEN col2
END
DROP TABLE #TestTable1
But this does NOT work. Returns:
Cannot convert a char value to money. The char value has incorrect syntax.
CREATE TABLE #TestTable2
(col1 money, col2 varchar(20))
INSERT INTO #TestTable2
(col1, col2)
VALUES
(1, 'cc'),
(2, 'bb'),
(3, 'aa')
SELECT col1, col2
FROM #TestTable2
ORDER BY
CASE 2
WHEN 1 THEN col1
WHEN 2 THEN col2
END
DROP TABLE #TestTable2
I am using Azure SQL with compatibility level 150.
I have updated Title and Tags accordingly.
UPDATE 2:
I am trying to add a complication to #forpas solution in form of a second parameter which will tell the order. I have used CASE within CASE but this returns a number of syntax errors.
The ORDER part only. The rest has not changed.
ORDER BY
CASE #SORTORDER
WHEN 'a' THEN
(CASE #SORTCOLUMN
WHEN 1 THEN col1
WHEN 2 THEN col2
END,
CASE #SORTCOLUMN
WHEN 3 THEN col3
WHEN 4 THEN col4
END) ASC
WHEN 'd' THEN
(CASE #SORTCOLUMN
WHEN 1 THEN col1
WHEN 2 THEN col2
END,
CASE #SORTCOLUMN
WHEN 3 THEN col3
WHEN 4 THEN col4
END) DESC
END
One solution is to split the CASE statement to as many CASE statements needed so each one contains columns with the same or similar convertable data types:
CREATE TABLE #TestTable2
(col1 money, col2 decimal(18, 2), col3 varchar(20))
INSERT INTO #TestTable2
(col1, col2, col3)
VALUES
(1, 5.5, 'cc'),
(2, 1.8, 'bb'),
(3, 3.3, 'aa');
DECLARE #SORTCOLUMN INT = 1; -- 1 or 2 or 3
SELECT col1, col2, col3
FROM #TestTable2
ORDER BY
CASE #SORTCOLUMN
WHEN 1 THEN col1
WHEN 2 THEN col2
END,
CASE #SORTCOLUMN
WHEN 3 THEN col3
END
DROP TABLE #TestTable2
See the demo.
Simply create the SQL as nvarchar and execute it as follows:
DECLARE #SQL NVARCHAR(MAX) = N'SELECT a, b, c FROM DataTable
WHERE c = #PARAM
ORDER BY ' + (CASE #SORTCOLUMN WHEN 1 THEN 'a' WHEN 2 THEN 'b' WHEN 3 THEN 'c' ELSE 'a' END);
EXEC sp_Executesql #SQL;
in VB
query as String = "DECLARE #SQL NVARCHAR(MAX) = N'SELECT a, b, c FROM DataTable
WHERE c = #PARAM
ORDER BY ' + (CASE #SORTCOLUMN WHEN 1 THEN 'a' WHEN 2 THEN 'b' WHEN 3 THEN 'c' ELSE 'a' END);
EXEC sp_Executesql #SQL;"
try this.
query as String = "
SELECT a, b, c
FROM DataTable
WHERE c = #PARAM
ORDER BY
CASE #SORTCOLUMN
WHEN '1' THEN a
WHEN '2' THEN b
WHEN '3' THEN c
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

How do I hash a column of a table in SQL Server?

I receive raw data files from external sources and need to provide analysis on them. I load the files into a table & set the fields as varchars, then run a complex SQL script that does some automated analysis. One issue I've been trying to resolve is: How to tell if a column of data is duplicated with 1 or more other columns in that same table?
My goal is to have, for every column, a hash, checksum, or something similar that looks at a column's values in every row in the order they come in. I have dynamic SQL that loops through every field (different tables will have a variable number of columns) based on the fields listed in INFORMATION_SCHEMA.COLUMNS, so no concerns on how to accomplish that part.
I've been researching this all day but can't seem to find any sensible way to hash every row of a field. Google & StackOverflow searches return how to do various things to rows of data, but I couldn't find much on how to do the same thing vertically on a field.
So, I considered 2 possibilities & hit 2 roadblocks:
HASHBYTES - Use 'FOR XML PATH' (or similar) to grab every row & use a delimiter between each row, then use HASHBYTES to hash the long string. Unfortunately, this won't work for me since I'm running SQL Server 2014, and HASHBYTES is limited to an input of 8000 characters. (I can also imagine performance would be abysmal on tables with millions of rows, looped for 200+ columns).
CHECKSUM + CHECKSUM_AGG - Get the CHECKSUM of each value, turning it into an integer, then use CHECKSUM_AGG on the results (since CHECKSUM_AGG needs integers). This looks promising, but the order of the data is not considered, returning the same value on different rows. Plus the risk of collisions is higher.
The second looked promising but doesn't work as I had hoped...
declare #t1 table
(col_1 varchar(5)
, col_2 varchar(5)
, col_3 varchar(5));
insert into #t1
values ('ABC', 'ABC', 'ABC')
, ('ABC', 'ABC', 'BCD')
, ('BCD', 'BCD', NULL)
, (NULL, NULL, 'ABC');
select * from #t1;
select cs_1 = CHECKSUM(col_1)
, cs_2 = CHECKSUM(col_2)
, cs_3 = CHECKSUM(col_3)
from #t1;
select csa_1 = CHECKSUM_AGG(CHECKSUM([col_1]))
, csa_2 = CHECKSUM_AGG(CHECKSUM([col_2]))
, csa_3 = CHECKSUM_AGG(CHECKSUM([col_3]))
from #t1;
In the last result set, all 3 columns bring back the same value: 2147449198.
Desired results: My goal is to have some code where csa_1 and csa_2 bring back the same value, while csa_3 brings back a different value, indicating that it's its own unique set.
You could compare every column combo in this way, rather than using hashes:
select case when count(case when column1 = column2 then 1 else null end) = count(1) then 1 else 0 end Column1EqualsColumn2
, case when count(case when column1 = column3 then 1 else null end) = count(1) then 1 else 0 end Column1EqualsColumn3
, case when count(case when column1 = column4 then 1 else null end) = count(1) then 1 else 0 end Column1EqualsColumn4
, case when count(case when column1 = column5 then 1 else null end) = count(1) then 1 else 0 end Column1EqualsColumn5
, case when count(case when column2 = column3 then 1 else null end) = count(1) then 1 else 0 end Column2EqualsColumn3
, case when count(case when column2 = column4 then 1 else null end) = count(1) then 1 else 0 end Column2EqualsColumn4
, case when count(case when column2 = column5 then 1 else null end) = count(1) then 1 else 0 end Column2EqualsColumn5
, case when count(case when column3 = column4 then 1 else null end) = count(1) then 1 else 0 end Column3EqualsColumn4
, case when count(case when column3 = column5 then 1 else null end) = count(1) then 1 else 0 end Column3EqualsColumn5
, case when count(case when column4 = column5 then 1 else null end) = count(1) then 1 else 0 end Column4EqualsColumn5
from myData a
Here's the setup code:
create table myData
(
id integer not null identity(1,1)
, column1 nvarchar (32)
, column2 nvarchar (32)
, column3 nvarchar (32)
, column4 nvarchar (32)
, column5 nvarchar (32)
)
insert myData (column1, column2, column3, column4, column5)
values ('hello', 'hello', 'no', 'match', 'match')
,('world', 'world', 'world', 'world', 'world')
,('repeat', 'repeat', 'repeat', 'repeat', 'repeat')
,('me', 'me', 'me', 'me', 'me')
And here's the obligatory SQL Fiddle.
Also, to save you having to write this here's some code to generate the above. This version will also include logic to handle scenarios where both columns' values are null:
declare #tableName sysname = 'myData'
, #sql nvarchar(max)
;with cte as (
select name, row_number() over (order by column_id) r
from sys.columns
where object_id = object_id(#tableName, 'U') --filter on our table
and name not in ('id') --only process for the columns we're interested in
)
select #sql = coalesce(#sql + char(10) + ', ', 'select') + ' case when count(case when ' + quotename(a.name) + ' = ' + quotename(b.name) + ' or (' + quotename(a.name) + ' is null and ' + quotename(b.name) + ' is null) then 1 else null end) = count(1) then 1 else 0 end ' + quotename(a.name + '_' + b.name)
from cte a
inner join cte b
on b.r > a.r
order by a.r, b.r
set #sql = #sql + char(10) + 'from ' + quotename(#tableName)
print #sql
NB: That's not to say you should run it as dynamic SQL; rather you can use this to generate your code (unless you need to support the scenario where the number or name of columns may vary at runtime, in which case you'd obviously want the dynamic option).
NEW SOLUTION
EDIT: Based on some new information, namely that there may be more than 200 columns, my suggestion is to compute hashes for each column, but perform it in the ETL tool.
Essentially, feed your data buffer through a transformation that computes a cryptographic hash of the previously-computed hash concatenated with the current column value. When you reach the end of the stream, you will have serially-generated hash values for each column, that are a proxy for the content and order of each set.
Then, you can compare each to all of the others almost instantly, as opposed to running 20,000 table scans.
OLD SOLUTION
Try this. Basically, you'll need a query like this to analyze each column against the others. There is not really a feasible hash-based solution. Just compare each set by its insertion order (some sort of row sequence number). Either generate this number during ingestion, or project it during retrieval, if you have a computationally-feasible means of doing so.
NOTE: I took liberties with the NULL here, comparing it as an empty string.
declare #t1 table
(
rownum int identity(1,1)
, col_1 varchar(5)
, col_2 varchar(5)
, col_3 varchar(5));
insert into #t1
values ('ABC', 'ABC', 'ABC')
, ('ABC', 'ABC', 'BCD')
, ('BCD', 'BCD', NULL)
, (NULL, NULL, 'ABC');
with col_1_sets as
(
select
t1.rownum as col_1_rownum
, CASE WHEN t2.rownum IS NULL THEN 1 ELSE 0 END AS col_2_miss
, CASE WHEN t3.rownum IS NULL THEN 1 ELSE 0 END AS col_3_miss
from
#t1 as t1
left join #t1 as t2 on
t1.rownum = t2.rownum
AND isnull(t1.col_1, '') = isnull(t2.col_2, '')
left join #t1 as t3 on
t1.rownum = t3.rownum
AND isnull(t1.col_1, '') = isnull(t2.col_3, '')
),
col_1_misses as
(
select
SUM(col_2_miss) as col_2_misses
, SUM(col_3_miss) as col_3_misses
from
col_1_sets
)
select
'col_1' as column_name
, CASE WHEN col_2_misses = 0 THEN 1 ELSE 0 END AS is_col_2_match
, CASE WHEN col_3_misses = 0 THEN 1 ELSE 0 END AS is_col_3_match
from
col_1_misses
Results:
+-------------+----------------+----------------+
| column_name | is_col_2_match | is_col_3_match |
+-------------+----------------+----------------+
| col_1 | 1 | 0 |
+-------------+----------------+----------------+

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

Stored procedure setting a value if row is empty

How would I go about setting a value if a row is empty ('')?
I was thinking something like,
Got var with default value called #defaultValue to set it where the row in a table is ''.
if (select col1 from table1 where col1 = '')
set (select col1 from table1 where col1 = '') = #DefaultValue
is there a better way?
code is just a draft its not even tested..
If you want to update the table with #DefaultValue, you can use WHERE clause in the UPDATE query:
UPDATE table1
SET col1=#DefaultValue
WHERE col1=''
OR col1 IS NULL
OR
If you are trying to select #DefaultValue if the column is empty or null, you can do this:
SELECT CASE WHEN (col1 IS NULL OR col1='')
THEN #DefaultValue
ELSE col1
END AS Col1
FROM table1
select case when col1 ='' then #DefaultValues else col1 end from table
DEMO
declare #default int
set #default=1
declare #tbl table(col1 int)
insert into #tbl values(1),(''),(2)
select case when col1='' or col1 is null then #default else col1 end from #tbl