SQL server, Find all columns that are contained in a string - sql

Suppose I have a table:
Id int,
Name varchar(10)
with values:
(1, Nick), (2, Mike), (3, Eric)
I want to return all the names that are contained in a string. For example "Nick, Mick" would return Nick and Mike.
I've tried with LIKE but it works the other way around returning the values that contain a string.
I was hoping for somthing like this, but that it actually works.
SELECT * FROM table
WHERE Name.isContained("Nick, Mike");
Result:
1, Nick and 2, Mike

Try this:
SELECT Name
FROM mytable
WHERE PATINDEX('%'+Name+'%', 'Nick, Mike') > 0
Demo here

Try this:
select name from tbl_sound where SOUNDEX(`name`) like '%00%'

Demo. Finds exact names match
create table demo (
Id int,
Name varchar(10));
insert demo
values
(1, 'Nick'), (2, 'Mike'), (3, 'Eric');
declare #prm varchar(200) = 'Nick,Mike,Ann';
select *
from demo
where ','+ #prm +',' like '%,'+Name+',%'
;

Check This.
declare #tmp nvarchar(250)
SET #tmp = ''
select #tmp = #tmp + concat(ID,' , ',name,' and ')
from table
where Name in ('Nick','Mike')
select SUBSTRING(#tmp, -2, LEN(#tmp))
OutPut :

Related

How to compare String Variable with Integer

I have this table structure and and some sample data. I want return data for multiple ids via parameter. I have declared a parameter string and now I want to compare it with the column but it ain't allowing because ID is integer.
Can anybody give me any help here ?
CREATE TABLE EMPLOYEE
(
ID INT,
EMPLOYEE_NAME VARCHAR(50)
);
INSERT INTO EMPLOYEE VALUES (1, 'Isaac Frempong');
INSERT INTO EMPLOYEE VALUES (2, 'Eric Ortizz');
DECLARE #StrID VARCHAR(20) = '1, 2'
SELECT * FROM EMPLOYEE
WHERE ID = #StrID
SELECT * FROM EMPLOYEE
WHERE #StrID+',' LIKE '%'+cast(ID as varchar(20))+'%,'
Pretty bad performance as it will need to do a table scan but safe enough.
Generally though, your list of IDs should be a table variable you can do a proper JOIN or IN with
The easiest solution is to use dynamic SQL
DECLARE #sql VARCHAR(1000) = 'SELECT * FROM EMPLOYEE WHERE ID IN (' + #StrID + ')';
EXEC(#sql);
For SQL Server 2017+ you could use STRING_SPLIT a table-valued function that splits a string into rows of substrings
CREATE TABLE EMPLOYEE
(
ID INT,
EMPLOYEE_NAME VARCHAR(50)
);
INSERT INTO EMPLOYEE VALUES (1, 'Isaac Frempong');
INSERT INTO EMPLOYEE VALUES (2, 'Eric Ortizz');
DECLARE #StrID VARCHAR(20) = '1, 2'
SELECT * FROM EMPLOYEE
WHERE ID IN (SELECT value FROM STRING_SPLIT (#StrID,','))
Refer this working fiddle
Create a user defined table type and pass it as a parameter.
CREATE TYPE [UDT_INTIDS] AS TABLE(
[ID] [int] NOT NULL
)
GO
-- create a table value
DECLARE #IDs [UDT_INTIDS];
INSERT #IDs VALUES (1),(2);
-- search using table value.
SELECT e.*
FROM EMPLOYEE e
WHERE e.ID IN (SELECT p.ID FROM #IDs p);
-- or
SELECT e.*
FROM EMPLOYEE e
JOIN #IDs p ON e.ID = p.ID;
See https://learn.microsoft.com/en-us/sql/relational-databases/tables/use-table-valued-parameters-database-engine?view=sql-server-2017 for more details.
You can use the Cast in SQL-Server to cast it to the appropriate datatype. Source Here
WHERE CAST(ID AS VARCHAR(20)) = #StrID
Alternatively: You can use CONVERT function.
WHERE CONVERT(VARCHAR(20), ID) = #StrID

Remove value from string where it match another column

I need to remove a file path from the beginning of a column. I have table with 3 columns one has just the path I want to remove.
So I have a table like:
Is there any way in SQL Server 2008 that I can remove the text where it matches the path column?
Thanks
Try this
UPDATE Table x
SET x.dataconv = SUBSTRING(x.dataconv,LEN(x.path),LEN(x.dataconv))
WHERE SUBSTRING(x.dataconv,1,LEN(x.path)) == x.path
You could try using replace?
DECLARE #table TABLE (id INT, dataconv VARCHAR(500), [path] VARCHAR(500));
INSERT INTO #table SELECT 1, 'C:\windows test_data_1', 'C:\windows';
INSERT INTO #table SELECT 2, 'C:\windows\test.ini test_data_2', 'C:\windows\test.ini';
INSERT INTO #table SELECT 3, 'C:\word docs\doc.ini test_data_3', 'C:\word docs\doc.ini';
INSERT INTO #table SELECT 4, '/P/TestUser/dfg002/SinglePageCV''s/JoeBloggs.doc33216root;tuser002_admin#IEroot;D‌​omain:Users#IE431104 1330820929 1003750078 1055597658', '/P/TestUser/dfg002/SinglePageCV''s/JoeBloggs.doc';
SELECT id, LTRIM(REPLACE(dataconv, [path], '')) FROM #table;
Returns:
1 test_data_1
2 test_data_2
3 test_data_3
4 33216root;tuser002_admin#IEroot;D??omain:Users#IE431104 1330820929 1003750078 1055597658

how to pick only last string

I have data like this I have seen functions and Substring and LEFT ,RIGHT also
but it is not serving my purpose
declare #t table (val varchar(50))
INSERT INTO #t(val)values ('E-001GHDEM120ENDORSEMENT'),
('E-001GHDEM120Renewal'),
('E-001GHDEM120Adjustment'),
('E-001GHDEM120ENDORSEMENT')
select * from #t
output
ENDORSEMENT
Renewal
Adjustment
ENDORSEMENT
I need to use that statement in where condition to filter records
Try this select
DECLARE #t TABLE
(
val VARCHAR(50)
);
INSERT INTO #t
(val
)
VALUES
('E-001GHDEM120ENDORSEMENT'
),
('E-001GHDEM120Renewal'
),
('E-001GHDEM120Adjustment'
),
('E-001GHDEM120ENDORSEMENT'
);
SELECT REVERSE(SUBSTRING(REVERSE(val), 0, PATINDEX('%[^a-zA-Z]%', REVERSE(val)))) AS val
FROM #t;
Try This. From your example here is what i understood.
select right(val,patindex('%[0-9]%', reverse(val))-1)
from #t

Combine multiple SQL fields into 1 output row

Having a SQL table like
UserID |Attribute | Value
1 |Username | Marius
1 |Password | Fubar
I want to create an output like:
1 | Marius | Fubar
Maybe I'm just too tired to see it, doesn't sound too complicated, but I just can't seem to figure it out. Any help is appreciated.
Why don't you use self joins, ie. :
select u1.userid, u1.value, u2.value
from yourtable u1
inner join yourtable u2 on u2.userid=u1.userid
where u1.attribute='Username' and u2.attribute='Password';
Would something like...
SELECT userID,
GROUP_CONCAT (Value SEPARATOR '|')
FROM my_table
GROUP BY UserID;
be what you are looking for?
If you keep your data that way, you will need to do a crosstab query and pivot your rows into columns. If you are using Microsoft SQL Server, check out "crosstab query" and the pivot operator in Books Online.
Edited:
One column per result:
If you try to combine multiple Attributes with the same UserID it would be something like this:
Short query (one UserID):
declare #concattedtext varchar(1000)
SELECT #concattedtext=coalesce(#concattedtext + '|', '') + Value
FROM #users WHERE UserID=1
SELECT #concattedtext
RESULT with your example data:
1 | Marius | Fubar
Full query (all UserID's)
-- Your source table
CREATE Table #users (UserID int, Attribute varchar(50), Value varchar(50))
-- some entries
INSERT into #users (UserID, Attribute, Value)
VALUES (1, 'Test1', 'attr1')
INSERT into #users (UserID, Attribute, Value)
VALUES (1, 'Test2', 'attr2')
INSERT into #users (UserID, Attribute, Value)
VALUES (1, 'Test3', 'attr3')
INSERT into #users (UserID, Attribute, Value)
VALUES (2, 'Test4', 'attr4')
-- ids table variable (for distinct UserID's)
DECLARE #ids TABLE
(
rownum int IDENTITY (1, 1) Primary key NOT NULL,
UserID int
)
-- Output table variable
DECLARE #out TABLE
(
rownum int IDENTITY (1, 1) Primary key NOT NULL,
UserID int,
ConcatText varchar(1000)
)
-- get distinct id's
INSERT INTO #ids(UserID)
SELECT DISTINCT(UserID) FROM #users
-- Foreach vars
declare #RowCnt int
declare #MaxRows int
select #RowCnt = 1
select #MaxRows=count(*) from #ids
-- UserID
declare #id int
declare #concattedtext varchar(1000)
-- process each id
while #RowCnt <= #MaxRows
begin
SET #id = 0
SELECT #id=UserID
FROM #ids WHERE rownum=#RowCnt
SET #concattedtext = CONVERT(nvarchar(50), #id)
FROM #ids WHERE rownum=#RowCnt
SELECT #concattedtext=coalesce(#concattedtext + '|', '') + Value
FROM #users WHERE UserID=#id
INSERT INTO #out(UserID, ConcatText)
VALUES (#id, #concattedtext)
-- next UserID
Select #RowCnt = #RowCnt + 1
end
SELECT * FROM #out
DROP TABLE #users
Result:
rownum|UserID|ConcatTex
1 | 1 |1|attr1|attr2|attr3
2 | 2 |2|attr4
DROP TABLE #users
You might need a sort field to get your parameters in your requested order.
Multiple columns
Your data needs to have an equal count of attributes if you like to get a table with multiple columns. And you still need to take care about the ordering.
In this case a hardcoded query with a group by would be your choice.

display all column with one column masked

I have two columns - name and ccNumber. I want to display both the column with one of them masked.
This query is showing only one column but I want all column to be displayed:
declare #t table (card_no varchar(20))
insert into #t
select ccNUMBER from ccinfo
select 'XXXX-XXXX-XXXX-'+ substring(card_no, 13, 4) as card_no from #t
i want name column with ccnumber column to be masked
You can try below
declare #t table (name varchar(100),card_no varchar(20))
insert into #t
select name, ccNUMBER from ccinfo
select name, 'XXXX-XXXX-XXXX-'+ substring(card_no, 13, 4) as card_no from #t
check the following example. i think you need concatenation of columns.
create table demo
(
firstName varchar(30),
secondName varchar(30)
);
insert into demo
values
('soumyajit', 'chatterjee'),
('papai', 'chatterjee'),
('virat', 'kohli');
select concat(firstName, ' ', secondName)as Name from demo;
You need to get the second column, too:
declare #t table (card_no varchar(20), name varchar(64));
insert into #t
select ccNUMBER, name from ccinfo
select 'XXXX-XXXX-XXXX-'+ substring(card_no, 13, 4) as card_no, name from #t
or just use the original table:
select 'XXXX-XXXX-XXXX-'+ substring(ccNUMBER, 13, 4) as card_no, name from ccinfo