How to combine If statement with Substring command in SQL? - sql

I have two types of entries in one column. One type starts with V2, the other starts with a digit. How do I write a query in SQL where I can extract different part of the string based on how it starts?
TextStringColumn
V2|T:GSK|1000000|S1:TES|S2:N/A|Q:24|S:0.5gx3|PD:2020-10-22|C:QQ
2000308|S1:BES|T:SKY|Q:16446G|BSI:BPKGVAXQOHZFWGE
I wrote
SELECT TextStringColumn, If(TextStringColumn like 'V2%',SUBSTRING(TextStringColumn ,10,7),SUBSTRING(TextStringColumn ,1,7)) As NumberCol
FROM TestTable
But I keep getting syntax errors.
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'If'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near ','.
The desired result will be
TextStringColumn NumberCol
V2|T:GSK|1000000|S1:TES|S2:N/A|Q:24|S:0.5gx3|PD:2020-10-22|C:QQ 1000000
2000308|S1:BES|T:SKY|Q:16446G|BSI:BPKGVAXQOHZFWGE 2000308

You may use a CASE expression:
SELECT
CASE WHEN TextStringColumn LIKE 'V2%'
THEN SUBSTRING(TextStringColumn, 10, 7)
ELSE SUBSTRING(TextStringColumn, 1, 7) END AS NumberCol
FROM TestTable;
The above logic assumes the only two varieties of strings are those which start with V2, and those which do not start with V2.

If the strings are variable length ... consider a little JSON
Example
Declare #YourTable Table ([TextStringColumn] varchar(100)) Insert Into #YourTable Values
('V2|T:GSK|1000000|S1:TES|S2:N/A|Q:24|S:0.5gx3|PD:2020-10-22|C:QQ')
,('2000308|S1:BES|T:SKY|Q:16446G|BSI:BPKGVAXQOHZFWGE')
Select A.*
,Val = case when [TextStringColumn] like 'V2%'
then JSON_VALUE(S,'$[2]')
else JSON_VALUE(S,'$[0]') end
From #YourTable A
Cross Apply ( values ( '["'+replace([TextStringColumn],'|','","')+'"]' ) ) B(S)
Returns
TextStringColumn Val
V2|T:GSK|1000000|S1:TES|S2:N/A|Q:24|S:0.5gx3|PD:2020-10-22|C:QQ 1000000
2000308|S1:BES|T:SKY|Q:16446G|BSI:BPKGVAXQOHZFWGE 2000308

Related

How to test a condition in a sql case statement on numbers

I would like to substitute all the values that are greater or equal to 10 with an empty string with a SQL CASE statement on my Microsoft SQL Server 2017. However, I am getting an error that reads:
Msg 102, Level 15, State 1, Line 13
Incorrect syntax near '>'.
Though there are some questions similar to my question, I can not find an answer that is specifically answering my question. For example this question here how to use > = condition in sql case statement?. I have also tried a dynamic query with a temporal table and this did not help.
Here is my code with the table definition and the test data as well as the actual query that I am running.
--table definition with two columns
declare #table table
(
person nvarchar(20),
digit decimal(10,2)
)
--insert test data with two records
insert into #table
select 'titimo', 9.51
union
select 'neriwo', 12.25
--the requirement is to not show the digit value if it is greater or equal to 10, but rather display an empty field.
--so, this is my select statement to meet this requirement that is failing
--with error message 'Incorrect syntax near >'
select
person,
case digit
when digit >= 10 then ''
else digit
end 'digit'
from #table
From my select statement above, I am expecting this output:
person digit
------ -----
titimo 9.51
neriwo
However, the output is not being generated because of the error message that I am experiencing.
You had a syntax error in your case. More over you cannot mix datatypes so you need to cast digit to varchar or change '' i.e. to null.
select
person,
case
when digit >= 10 then ''
else cast(digit as varchar(20))
end 'digit'
from #table
Your case is not formatted correctly - here's one option -
(also, you can't select text and numbers in the same column - so I casted your number to text... tweak to fit your needs)
select
person,
case when digit >=10 then ''
else CONVERT(VARCHAR(10), digit)
end 'digit'
from #table

what's wrong with this bit of code

declare
cursor c_pointage is select * from pointage;
v_pointage c_pointage%rowtype;
v_date nvarchar;
v_heures int ;
v_minutes int ;
begin
for v_pointage in c_pointage loop
v_date:= CONVERT(varchar(10), v_pointage.DateHeureArrivee, 120) ;
v_heures := DATEPART(hour, v_pointage.DateHeureArrivee);
v_minutes := DATEPART(minute, v_pointage.DateHeureArrivee);
insert into Calc_pointage values ( v_pointage.ID, v_pointage.Nom, v_pointage.Departement, v_pointage.NumCarte, v_pointage.IDterminale, v_pointage.NomTerminale, v_pointage.IDInOut,v_date,v_heures,v_minutes);
end loop;
end ;
i keep getting these errors :
Incorrect syntax near the keyword 'cursor'.
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near 'v_pointage'.
Msg 102, Level 15, State 1, Line 13
Incorrect syntax near 'loop'.
ps : the data type from the table i'm inserting from match the one i'm inserting into
You shouldn't be writing a cursor for this at all. INSERT ... SELECT should do the job:
insert into Calc_pointage (/*TODO - Column list */)
select
ID, Nom, Departement, NumCarte, IDterminale, NomTerminale, IDInOut,
CONVERT(varchar(10), DateHeureArrivee, 120), --Ideally, CONVERT(date,DateHeureArrivee) instead
DATEPART(hour, DateHeureArrivee),
DATEPART(minute, DateHeureArrivee)
FROM pointage
But now I look at this, this also smells distinctively of your having decided to break a process down into a series of procedural steps (why are you just copying one table into another?) when the whole thing should probably just be a CTE as part of a single set-based query.
A key thing to get your head aroung when transitioning to writing SQL is to "think in sets". Try not to break the problem down, or at least, don't break it down into loops and how to process a single row at a time. If your input data doesn't resemble what you want, think about how to transform the entire set of rows into a set of rows that more closely resembles what you're looking for. Then write a CTE that does that transformation, and build from there.

i try to combine rows in one column but there was an error in my syntax

select
Elm_EmployeeId as 'Badge',
Left(T_EmployeeLeave , Len(T_EmployeeLeave) - 1) As 'a'
from
(select
E2.Elm_EmployeeId as 'Badge2',
(select Elm_EmployeeId
from T_EmployeeLeave E1)
from
T_EmployeeLeave E2)
Error is:
Msg 102, Level 15, State 1, Line 8
Incorrect syntax near ')'.
1.you select Elm_EmployeeId and T_EmployeeLeave from a subquery but in the subquery u don't have these two columns what you have is badge2 and a non_named column
the select Elm_EmployeeId from T_EmployeeLeave E1 is meaningless
the query is miserable i can't even tell what excatly you want

Apply IsNull function on a date column (SQL Server)

I am trying to apply the IsNull function to a column of a datatype date.
What am trying to do is, to replace the word NULL with an empty string (actual null value) when retrieving the data
The code am using is;
Select
ISNULL("UPDATE_DT", '')
from
MyTable
I have also tried
Select
ISNULL("UPDATE_DT", 0)
from
MyTable
The error am getting is
Msg 103010, Level 16, State 1, Line 1
Parse error at line: 4, column: 1: Incorrect syntax near 'from'.
If you want to see the column as an empty string rather than "NULL", you need to convert the output to a string. To control the format, use convert():
select coalesce(convert(varchar(10), update_dt, 121), '')
. . .
Then use coalesce() (or if you must, isnull()) to replace the NULL value with another string.

Incorrect syntax near ',' SQL Server Error

I am having the following error on my SQL Server Query I don't know how to overcome it Because I tried my best Please help me getting out of it:
CREATE TABLE d3 as SELECT sessionnumber, sessioncount, LEFT(timespent, 1) , COUNT
as cnt
FROM clusters
GROUP BY 1, 2, 3
The following error is generated:
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near ','.
Please help me! Thanks in advance
This is not SQL Server syntax. You want select into:
SELECT sessionnumber, sessioncount, LEFT(timespent, 1) as TimeSpentCode, COUNT(*) as cnt
into d3
FROM clusters
GROUP BY sessionnumber, sessioncount, LEFT(timespent, 1);
All the columns need to have names. So I added one for the third column.
And, group by does not accept positional indicators in SQL Server, so I replaced them with the appropriate expressions.
You have the word count instead of count(something).