SQL Select removing characters from a column - sql

I need a "replace" select query that strips everything but 3 characters after a string.
Example:
Data = "CN=GOT002086,OU=LAPTOPS,OU=COMPUTERS,OU=GOT,DC=CORP,DC=GDS,DC=COMPANYNAME,DC=COM"
I need to replace the output of this field to only show "GOT". I figured I could key on the word "COMPUTERS" within the column and if possible select only the 3 characters 4 spaces after the word "COMPUTERS". This column is a fully qualified computer name and I only want the OU to be shown.

Try this.
DECLARE #TestString VARCHAR(1000)
SET #TestString = 'CN=GOT002086,OU=LAPTOPS,OU=COMPUTERS,OU=GOT,DC=CORP,DC=GDS,DC=COMPANYNAME,DC=COM'
SELECT SUBSTRING(#TestString, CHARINDEX('COMPUTERS,', #TestString ,0)+13,3)
Updated
CREATE TABLE ActualValuesTable (ValueColumn VARCHAR(250))
INSERT INTO ActualValuesTable VALUES('CN=GOT002086,OU=LAPTOPS,OU=COMPUTERS,OU=GOT,DC=CORP,DC=GDS,DC=COMPANYNAME,DC=COM')
INSERT INTO ActualValuesTable VALUES('CN=GOT002086,OU=LAPTOPS,OU=COMPUTERS,OU=123,DC=CORP,DC=GDS,DC=COMPANYNAME,DC=COM')
INSERT INTO ActualValuesTable VALUES('SomeText..OU=COMPUTERS,OU=789,SomeText..')
INSERT INTO ActualValuesTable VALUES('SomeText..OU=COMPUTERS,OU=012,SomeText..')
INSERT INTO ActualValuesTable VALUES('SomeText..OU=COMPUTERS,OU=234,SomeText..')
INSERT INTO ActualValuesTable VALUES('SomeText..OU=COMPUTERS,OU=456,SomeText..')
SELECT SUBSTRING(ValueColumn, CHARINDEX('COMPUTERS,', ValueColumn ,0)+13,3) FROM ActualValuesTable

Related

Create a procedure to insert multiple values into a table, using a single variable

Goal: To create a procedure to insert multiple values into a table, using a single variable.
Challenge: Instead of making multiple hits in the same table, I have created a single variable (#SQL) and stored multiple columns (fm_id and shdl_id ) results in it but I am unable to use this single variable in the insert statement.
Code:
create proc abc
(
#org_id numeric(10,0),
#shdl_id numeric(10,0),
#usr_id numeric(10,0),
#tst_id numeric(10,0)
)
AS
BEGIN
SET NOCOUNT ON
DECLARE #SQL NUMERIC(10);
SET #SQL= (SELECT fm_id,#shdl_id FROM [dbo].[students] WHERE ORG_ID=#org_id AND shdl_id=#shdl_id AND TST_ID=#tst_id)
INSERT INTO [USER]
SELECT org_id,#usr_id,TST_ID,login_name,#SQL FROM [students] WHERE ORG_ID=#org_id AND shdl_id=#shdl_id AND TST_ID=#tst_id
END
GO
Error :
Msg 213, Level 16, State 1, Procedure abc, Line 14 [Batch Start Line
94] Column name or number of supplied values does not match table
definition.
First you need to make your SELECT return only one value into the variable. There's no point selecting #shdl_id because you already know it?
DECLARE #pFMID NUMERIC(10);
SELECT #pFMID = MAX(fm_id) FROM [dbo].[students] WHERE ORG_ID=#org_id AND shdl_id=#shdl_id AND TST_ID=#tst_id);
Then because you're not inserting a value into every column in the user table you need to explicitly state which columns to fill. Replace x1..x5 below with real column names (in the order the SELECT has them)
INSERT INTO [USER](x1,x2,x3,x4,x5)
-- ^^^^^^^^^^^^^^^
-- REPLACE THESE WITH REAL NAME
SELECT org_id,#usr_id,TST_ID,login_name,#pFMID FROM [students] WHERE ORG_ID=#org_id AND shdl_id=#shdl_id AND TST_ID=#tst_id
END
GO
And as Uueerdo pointed out, this first query is a bit of a waste of time, we can write this:
create proc abc
(
...
)
AS
BEGIN
INSERT INTO [USER](x1,x2,x3,x4,x5)
SELECT org_id,#usr_id,TST_ID,login_name,fm_id FROM [students] WHERE ORG_ID=#org_id AND shdl_id=#shdl_id AND TST_ID=#tst_id
-- ^^^^^
-- look!
You can only get away with leaving the column list off an INSERT if you're inserting the same number of columns the table has:
CREATE TABLE x(col1 INT, col2 INT);
INSERT INTO x VALUES (1,2) -- works
INSERT INTO x VALUES (1) -- fails: which column should have the 1?
INSERT INTO x(col1) VALUES (1) -- works: col1 shall have the 1

T-SQL select special characters from nvarchar field

I'm looking for a select statement in which I can refine values in a nvarchar field.
For example: the input value is '!ab>c2 ghf5 ksj#_+wwl9' and output must be 'abc ghf ksjwwl'. How can I remove some extra characters within a text with SQL regex or other ways?
I don't know if this helps, but you can define a table with all characters / phrases you want to replace and do it like this:
DECLARE #CharsToReplace TABLE(SearchFor VARCHAR(100),ReplaceWith VARCHAR(100));
INSERT INTO #CharsToReplace VALUES('1',''),('2',''),('3',''),('4',''),('5',''),('6',''),('7',''),('8',''),('9',''),('0','');
DECLARE #YourString VARCHAR(100)='abc2 ghf5 ksjwwl9';
SELECT #YourString=REPLACE(#YourString,SearchFor,ReplaceWith)
FROM #CharsToReplace;
SELECT #YourString;
The result
abc ghf ksjwwl
If you'd define values in ReplaceWith this would work too.
UPDATE A function you can use in any select
Attention: This will be slow!
CREATE FUNCTION dbo.DeleteChars(#CharList NVARCHAR(MAX),#string NVARCHAR(MAX))
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE #List XML=(SELECT CAST('<x>'+ REPLACE(#CharList,',','</x><x>')+'</x>' AS XML));
SELECT #string=REPLACE(#string,ch.value(N'.',N'nvarchar(max)'),'')
FROM #List.nodes('/x') AS A(ch);
RETURN #string;
END
GO
--Test this with a mock-up table
DECLARE #SomeTable TABLE(SomeColumn VARCHAR(100));
INSERT INTO #SomeTable VALUES('abc2 ghf5 ksjwwl9'),('123 abc 456 hello');
--This is the char list (comma separated)
DECLARE #CharList VARCHAR(100)='1,2,3,4,5,6,7,8,9,0';
--This is how you call it
SELECT dbo.DeleteChars(#CharList,SomeColumn)
FROM #SomeTable
GO
--Clean up
DROP FUNCTION dbo.DeleteChars;
The result
abc ghf ksjwwl
abc hello

T-SQL to text: set column width as required

I've got a piece of sql script which I run with the output set to text.
The column it returns is set to varchar(255), so in the text output the column is 255 chars wide.
I know I can use
Cast(ColumnName As VarChar(75))) As ColumnName
to restrict it down to 75 characters width, but what I want to achieve is that it automatically sets the width to the widest result it returns. Does anyone know if this is possible?
Use dynamic query to achieve the result.
See one sample script below.
CREATE TABLE #temp
(Column1 VARCHAR(50))
INSERT INTO #temp (Column1) VALUES ('1111-123'),('15454454aa-4545')
DECLARE #Delimit INT
DECLARE #queryString VARCHAR(MAX)
SELECT #Delimit=MAX(LEN(Column1)) FROM #temp --Getting the Length of largest column data
SET #queryString='SELECT CAST(Column1 AS VARCHAR('+CONVERT(VARCHAR(50),#Delimit)+'))Column1
FROM #temp'
EXEC(#queryString)

T-SQL Replace Multiple Values with Wildcards

I want to replace characters , and /. I can do this with:
DECLARE #OMG VARCHAR(200)
SET #OMG = 'ABC,DE/F'
SELECT REPLACE(REPLACE(#OMG,'/','|') ,',','|')
The second query does not work however. Is there just typo or the task cannot be achieved with this code? I wanted to use wildcard for set of characters that should be replaced.
SELECT REPLACE(#OMG,[,/],'|')
It returns:
Msg 207, Level 16, State 1, Line 7
Invalid column name ',/'.
You can define all the variables to be replaced and the replacement inside a table use it.
create TABLE #ReplaceStrings (symb VARCHAR(5),replace_char varchar(5))
INSERT INTO #ReplaceStrings
(symb,replace_char)
VALUES ('/','|'),(',','|')
DECLARE #OMG VARCHAR(200)
SET #OMG = 'ABC,DE/F'
SELECT #OMG = Replace(#OMG, symb, replace_char)
FROM #ReplaceStrings
select #OMG
Here in a single replace you can replace all the unwanted characters.
Update: to replace data from table
create TABLE ReplaceStrings (symb VARCHAR(5),replace_char varchar(5))
create table #table (String varchar(500))
insert into #table values ('ABC,DE/F'),('AB,C,DE/F/')
INSERT INTO ReplaceStrings VALUES ('/','|'),(',','|')
Scalar Function
Create function replacechar(#Ip_String varchar(500))
returns varchar(500)
begin
SELECT #Ip_String=Replace(#Ip_String, symb, replace_char)
FROM ReplaceStrings
return #Ip_String
end
Execute the function
select String,dbo.replacechar(String) Replaced_String from #table

LIKE with Multiple Consecutive White Spaces

I have following query with LIKE predicate in SQL Server 2012. It replaces white spaces with %. I have two records in the table.
DECLARE #MyTable TABLE (ITMEID INT, ITMDESC VARCHAR(100))
INSERT INTO #MyTable VALUES (1,'Healty and Alive r')
INSERT INTO #MyTable VALUES (2, 'A liver patient')
DECLARE #SearchCriteria VARCHAR(100)
SET #SearchCriteria = 'Alive'
SELECT *
FROM #MyTable
WHERE (ITMDESC LIKE '%'+REPLACE(#SearchCriteria,' ','%')+'%' ESCAPE '\')
I got this query from a friend to consider multiple consequent white spaces as a single space. The challenge is I don't see any reference for this.
Is there a pitfall in the approach?
REPLACE(#SearchCriteria,' ','%') always returns Alive. There is no Alive word in the second row, therefore it's not returned.
In fact, WHERE clause will look like this: WHERE (ITMDESC LIKE '%Alive%' ESCAPE '\')
The second row doesn't meet it.
Probably, you want something like this:
SELECT *
FROM #MyTable
WHERE (REPLACE(ITMDESC,' ','') LIKE '%'+#SearchCriteria+'%' ESCAPE '\')
you can use as below
DECLARE #MyTable TABLE (ITMEID INT, ITMDESC VARCHAR(100))
INSERT INTO #MyTable VALUES (1,'Healty and Alive r')
INSERT INTO #MyTable VALUES (2, 'A liver patient')
ECLARE #SearchCriteria VARCHAR(100)
SET #SearchCriteria = 'Alive'
SELECT *
FROM #MyTable
WHERE (REPLACE(ITMDESC,' ','') LIKE '%'+#SearchCriteria+'%' ESCAPE '\')
it will return both records as you want
The simplest solution is to replace all spaces with some moniker and then replace that moniker with a single space.
Select Replace(Replace(ItmDesc, ' ', '<z>'), '<z>', ' ')
From MyTable
SQL Fiddle version