I have table customer_info in which a column PrintData which contains many information. I would like to get Transaction id from that column.
The column data look like this:
<Line28>.TVR: 4000008000</Line28>
<Line29>.IAD: 06020103649D00</Line29>
<Line30>.TSI: E800</Line30>
<Line31>.ARC: 00</Line31>
<Line32>.CVM: PIN VERIFIED</Line32>
<Line33>.TRAN ID: 000000000075169</Line33>
I would like to get only 000000000075169 i.e. TRAN ID:
I have tried this as:
SUBSTRING(PrintData,CHARINDEX('TRAN ID: ',PrintData),CHARINDEX('</Li',PrintData))
but it is not giving write answer.
DECLARE #z NVARCHAR(MAX) = '
<Line28>.TVR: 4000008000</Line28>
<Line29>.IAD: 06020103649D00</Line29>
<Line30>.TSI: E800</Line30>
<Line31>.ARC: 00</Line31>
<Line32>.CVM: PIN VERIFIED</Line32>
<Line33>.TRAN ID: 000000000075169</Line33>
'
SELECT SUBSTRING(#z, CHARINDEX('TRAN ID: ', #z) + 9 -- offset charindex by 9 characters to omit the 'TRAN ID: '
, CHARINDEX('</Li', #z, CHARINDEX('TRAN ID: ', #z))-CHARINDEX('TRAN ID: ', #z) - 9) -- find the </Li AFTER the occurence of TRAN ID, and subract 9 to account for the offset
Yields 000000000075169.
Can you please with the following query.
DECLARE #PrintData AS VARCHAR (200) = '<Line33>.TRAN ID: 000000000075169</Line33>';
SELECT SUBSTRING(#PrintData,
CHARINDEX('TRAN ID: ', #PrintData) + LEN('TRAN ID: '),
CHARINDEX('</Li',#PrintData) - (CHARINDEX('TRAN ID: ', #PrintData) + LEN('TRAN ID: '))
);
The syntax is SUBSTRING (expression, start_position, length)
UPDATE:
As per the comment by MarcinJ, for the multiple instance of </Line, the folllowing query will work.
DECLARE #PrintData VARCHAR(2000) = '
<Line28>.TVR: 4000008000</Line28>
<Line29>.IAD: 06020103649D00</Line29>
<Line30>.TSI: E800</Line30>
<Line31>.ARC: 00</Line31>
<Line32>.CVM: PIN VERIFIED</Line32>
<Line33>.TRAN ID: 000000000075169</Line33>
';
DECLARE #FindString AS VARCHAR (20) = 'TRAN ID: ';
DECLARE #LenFindString AS INT = LEN(#FindString);
SELECT SUBSTRING(#PrintData,
CHARINDEX(#FindString, #PrintData) + #LenFindString,
CHARINDEX('</Line', #PrintData, CHARINDEX(#FindString, #PrintData)) - (CHARINDEX(#FindString, #PrintData) + #LenFindString)
);
I would simply use APPLY :
select #PrintData AS Original_string,
substring(tran_id, 1, charindex('</', tran_id) -1) as Tran_ID
from ( values ( substring(PrintData, charindex('TRAN ID:', PrintData) + 8, len(PrintData)) )
) t(tran_id);
Related
Can somebody please help me to understand why the IN() function does not work in any of the below attempts?
DECLARE #Company VARCHAR(50) = ('''ABC''' + ', ' + '''DEF''' + ', ' + '''VEG''' + ', ' + '''HIJ''') --+ WNY, VEG''')
PRINT #Company
PRINT IIF('VEG' IN (#Company), 'TRUE', 'FALSE');
DECLARE #Company2 VARCHAR(50) = ('''ABC, DEF, VEG, HIJ''')
PRINT #Company2
PRINT IIF('VEG' IN (#Company2), 'TRUE', 'FAL
Tried running the command as presented and both IIF()s return false.
I need to replace some characters in email string, exactly such actions:
lower_email = str.lower(str.split(email,'#')[0])
nopunc_email = re.sub('[!##$%^&*()-=+.,]', ' ', lower_email)
nonum_email = re.sub(r'[0-9]+', '', nopunc_email).strip()
But in SQL
I tried to use expression TRANSLATE(lower(email), 'a1_a.a-a#1-+()a ', 'a a a a'), but it didn't give me solution.
Thanks in advance!
For example:
import re
email = 'some_email.example-2021#gmail.com'
lower_email = str.lower(str.split(email,'#')[0])
nopunc_email = re.sub('[!#_#$%^&*()-=+.,]', ' ', lower_email)
nonum_email = re.sub(r'[0-9]+', '', nopunc_email).strip()
result 'some email example'
SELECT email,
TRIM(
TRANSLATE(
LOWER(SUBSTR(email, 1, INSTR(email, '#') - 1)),
'!_#$%^&*()-=+.,0123456789',
' '
)
) AS translated
FROM table_name
Which, for the sample data:
CREATE TABLE table_name (email) AS
SELECT 'some_email.example-2021#gmail.com' FROM DUAL;
Outputs:
EMAIL
TRANSLATED
some_email.example-2021#gmail.com
some email example
db<>fiddle here
HI I am writing SSIS package to get the output from
Select a,b,c from CUST FOR JSON AUTO
However I am getting output in a single row like
{"a":"Rock" ,"b":"paper" ,"c":"scissors"}, {"a":"Rock" ,"b":"paper" ,"c":"scissors"}, {"a":"Rock" ,"b":"paper" ,"c":"scissors"}....
However I want output as
{
"a":"Rock",
"b":"paper",
"c":"scissors"
},
{
"a":"Rock",
"b":"paper",
"c":"scissors"
},
{
"a":"Rock",
"b":"paper",
"c":"scissors"
},
My client argument is the Json file will be big file and he don't want to do extra formatting and should be readable
If you can add a javascript component to SSIS, it can be done.
(I'm not sure on how to do that in SSIS). But here is how you do it in javascript
I have a way to get this done rather messy way, but you can see whether that serves you the purpose
DECLARE #nl varchar(2) = char(13), #Json nvarchar(MAX) = (Select a,b,c from #CUST FOR JSON AUTO)
Select #Json = Replace(#Json, '[{','[' + #nl + '{' + #nl)
Select #Json = Replace(#Json, '{','{' + #nl)
Select #Json = Replace(#Json, '","','",' + #nl + '"' )
Select #Json = Replace(#Json, '"},{','"' + #nl + '},' + #nl + #nl + '{' )
Select #Json = Replace(#Json, '"}]','"' + #nl + '}' + #nl + ']' + #nl + #nl)
Select #Json as FormattedJSON
And here is the fiddle with more improvements
Hi I Have Table that called Tags, in tag table I have 2 columns (QuestionID int ,Tag nvachar(100))
I want to Select Questions with all Tags in one column like the below
QuestionID Tag
---------- ----
1 Math
1 Integral
2 Physics
QuestionID QuestionText
---------- -----------
1 What is 2*2?
2 What is Quantom roles?
QuestionID QuestionText Tags
---------- ----------- -------
1 What is 2*2? Math, Integral
2 What is Quantom roles? Physics
Can any one help me with out using scalar value function
There are two ways to answer this:
can use a query like in other answer, but this is work for one table only.
create clr aggregate function for this like a below code (my code in C#).
this solution work for all tables and simple for use,
only use: select Concat(column) from Table in sql server
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Text;
[Serializable]
[Microsoft.SqlServer.Server.SqlUserDefinedAggregate(Format.UserDefined, IsInvariantToDuplicates = false, IsInvariantToNulls = true, IsInvariantToOrder = false, IsNullIfEmpty = true, MaxByteSize = -1)]
public struct Concat : IBinarySerialize
{
public void Init()
{
SB = new StringBuilder();
}
public void Accumulate(SqlString Value)
{
if (Value.IsNull)
return;
if (SB.Length > 0)
SB.Append("\n");
SB.Append(Value);
}
public void Merge(Concat Group)
{
if (SB.Length > 0 && Group.SB.Length > 0)
SB.Append("\n");
SB.Append(Group.SB.ToString());
}
public SqlString Terminate()
{
return new SqlString(SB.ToString());
}
// This is a place-holder member field
StringBuilder SB;
public void Read(System.IO.BinaryReader r)
{
SB = new StringBuilder(r.ReadString());
}
public void Write(System.IO.BinaryWriter w)
{
w.Write(SB.ToString());
}
}
CREATE TABLE #temp
(
QuestionID INT,
Tag NVARCHAR(100)
)
INSERT INTO #temp
(QuestionID,Tag)
VALUES (1,N'Math'),
(1,N'Integral'),
(2,N'Physics')
CREATE TABLE #temp1
(
QuestionID INT,
QuestionText NVARCHAR(100)
)
INSERT INTO #temp1
(QuestionID,QuestionText)
VALUES (1,N'What is 2*2?'),
(2,'What is Quantom roles?')
SELECT h.QuestionID,
h.QuestionText,
Stuff((SELECT ', ' + CONVERT(VARCHAR, b.TAG)
FROM #temp b
WHERE b.QuestionID = h.QuestionID
FOR XML PATH('')), 1, 2, '')
FROM #temp t
JOIN #temp1 h
ON t.QuestionID = h.QuestionID
GROUP BY h.QuestionID,
h.QuestionText
SELECT q.QuestionText
,STUFF((
SELECT ', ' + t2.Tag
FROM Tags t2
WHERE t1.QuestionID = t2.QuestionID
ORDER BY t2.Tag
FOR XML PATH('')
,TYPE
).value('.', 'varchar(max)'), 1, 2, '') AS Tag
FROM Questions q
INNER JOIN Tags t1
ON q.QuestionID = t1.QuestionID
GROUP BY q.QuestionText
,t1.QuestionID
Working example : http://sqlfiddle.com/#!3/e8f0f/7
Try this
create function fn_comma (#question_id int)
returns varchar(100)
as
begin
declare #value varchar(100)
set #value=(SELECT top 1 STUFF((SELECT ', ' + CAST(Value AS VARCHAR(10)) [text()]
FROM Tags
WHERE ID = t.ID
FOR XML PATH(''), TYPE)
.value('.','NVARCHAR(MAX)'),1,2,' ') List_Output
FROM Tags
--where id=1
GROUP BY ID)
return #value
end
Try sub query to concat column data in comma separated values like below :
SELECT [QuestionID],
[QuestionText],
STUFF(( SELECT ',' + [Tag]
FROM [dbo].[Tags]
WHERE [QuestionID] = [Question].[QuestionID]
FOR XML PATH ('')), 1, 1, '') AS [Tags]
FROM [dbo].[Question]
SQL Fiddle Demo
Try the below idea. You just need to rewrite it as a function, then it will return all tags for the question id:
declare #function_in_questionid_para as #int
with std as
(select *,ROW_NUMBER() over(partition by QuestionID order by QuestionID,tag) as dd from #temp)
select * #temp3 into from std
declare #counter as int
set #counter = (select count(*) from #temp where QuestionID = #function_in_questionid_para as #int)
declare #c as int = 1
declare #tags as varchar(200) = ''
while (#c <= #counter)
begin
if (#c > 1) set #tags = #tags + ', '
set #tags = #tags + (select tag from #temp3 where QuestionID = #function_in_questionid_para as #int and dd = #c)
set #c = #c + 1
end
print #tags
I have a table with phone numbers in it. Instead of spitting out a single row for each number I want to return a comma separated list of phone numbers. What's the easiest way to do this in sql? A while loop?
Some of those answers are overly complicated with coalesce and more complex XML queries. I use this all the time:
select #Phones=(
Select PhoneColumn+','
From TableName
For XML Path(''))
-- Remove trailing comma if necessary
select #Phones=left(#Phones,len(#Phones)-1)
You could create a UDF that would do something like this
CREATE FUNCTION dbo.GetBirthdays(#UserId INT)
RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE #combined VARCHAR(MAX)
SELECT #combined = COALESCE(#combined + ', ' + colName + ', colName)
FROM YourTable
WHERE UserId = #UserId
ORDER BY ColName
END
Basically this just pulls all of the values into a simple list.
FWIW I created a SQL CLR Aggregate function. Works like a champ!
[Serializable]
[SqlUserDefinedAggregate(Format.UserDefined,
Name = "JoinStrings",
IsInvariantToNulls=true,
IsInvariantToDuplicates=false,
IsInvariantToOrder=false,
MaxByteSize=8000)] public struct
JoinStrings : IBinarySerialize {
public string Result;
public void Init()
{
Result = "";
}
public void Accumulate(SqlString value)
{
if (value.IsNull)
return;
Result += value.Value + ",";
}
public void Merge(JoinStrings Group)
{
Result += Group.Result;
}
public SqlString Terminate()
{
return new SqlString(Result.ToString().Trim(new
char[] { ',' }));
}
public void Read(System.IO.BinaryReader r)
{
Result = r.ReadString();
}
public void Write(System.IO.BinaryWriter w)
{
w.Write(Result.ToString());
} }
I can then use it like this:
SELECT dbo.JoinStrings(Phone) FROM Phones Where UserID = XXX
See my answer from this question. There are a couple of other ways to do it listed in that question also. COALESCE or for xml path should do the trick though.
Edit (added my answer from the previous question):
CREATE FUNCTION [dbo].[fn_MyFunction]()RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE #str NVARCHAR(MAX)
DECLARE #Delimiter CHAR(2)
SET #Delimiter = ', '
SELECT #str = COALESCE(#str + #Delimiter,'') + AColumn
FROM dbo.myTable
RETURN RTRIM(LTRIM(#str))
END
Assuming you have a Customers table which has a unique ID and another table named PhoneNumbers with multiple phone numbers for each customer sharing the Customer ID field as a Foreign Key this would work using a correlated sub-Query
Select C.ID, C.FirstName, C.LastName,
(select (STUFF(( SELECT ', ' + PhoneNumber from PhoneNumbers P where P.CID = C.ID
FOR XML PATH('')), 1, 2, ''))) as PhoneNumbers
from Customers C
Select Unique ID, Replace(Rtrim(Ltrim(Case when [Phone_Number1] is not null Then [Phone_Number1]+' ' Else '' End +
Case when [Phone_Number2] is not null Then [Phone_Number2]+' ' Else '' End +
Case when [Phone_Number3] is not null Then [Phone_Number3]+' ' Else '' End)),' ',', ') as Phone_numbers
From MYTable
Hope this is what you are looking for and I dont know if this will help you so far after the question.