how Remove certain character at Front and back of a varchar - sql

I have a customer data such as below
Table= Customer
field= CardNo
Data in CardNo:
%ABC?;9991?
%ABC?;99912?
%ABC?;999123?
%ABC?;888123?
Output i want is
9991
99912
999123
888123
However I want to remove all the "%ABC?;" at the front and "?" at the back, in the entire CardNo field. How I do it? I have tried this with no success:
UPDATE Customer
SET cardno = RIGHT(cardno, LEN(cardno) - 7)
I get an error:
"Return Error
Msg 536, Level 16, State 2, Line 1
Invalid length parameter passed to the RIGHT function.
The statement has been terminated."
What's wrong and how can I fix it?

Try like this...
UPDATE Table1 Set Cid=Replace(Left(Cid,Len(CID)-1),'%ABC?;','') FROM TABLE1
Sql Fiddle Demo

If you don't mean exactly this, you should probably be more clear what your intended result is:
DECLARE #foo VARCHAR(32)
SET #foo = '%ABC?;888123?'
SELECT SUBSTRING(#foo, 7, LEN(#foo) - 7)
Result: 888123
As applied to your code:
UPDATE Customer
SET cardno = SUBSTRING(cardno, 7, LEN(cardno) - 7)
Demo

REPLACE will work well. REPLACE('%ABC?;9991?', '%ABC?', '')
You can chain them together to remove the second ? as well.

Here is a rather brute force way, considering all possibilities for the pattern:
UPDATE Customer
SET cardno = (case when cardno like '[%]ABC[?];%[?]'
then substring(cardno, 6, len(cardno) - 7)
when cardno like '[%]ABC[?];%'
then substring(cardno, 6, len(cardno) - 6)
when cardno like '%[?]'
then substring(cardno, len(cardno) - 1)
else cardno
end)

Related

SQL Is it possible to incorporate a SELECT with a REPLACE?

I'm using MS SQL Server 2019
I have a string in a table (tblJobCosts) that has its own ID like this:
TextID jobText
1 Total Cost for job is £[]. This includes VAT
How do I update the value stored in the brackets based on the value from another table?
The end result would look like this:
Total Cost for job is £500. This includes VAT
I thought I could incorporate a SELECT with a REPLACE but this does not seem possible:
DECLARE #JobNum INT = 123;
UPDATE dbo.JobCosts
SET jobText = REPLACE (jobText,'[]',
SELECT JH.jobCost
FROM dbo.JobHead AS JH
WHERE (JH.JobNo = #JobNum)
) AND TextID = 1
If I run the above I receive the error:
Incorrect syntax near the keyword 'SELECT'.
Is it possible to incorporate a SELECT with a REPLACE?
I think that you cannot call a select statement in the replace function.
I would try something like that:
UPDATE dbo.JobCosts
SET jobText = REPLACE (jobText,'[]',k.the_cost) from
( SELECT JH.jobCost as the_cost
FROM dbo.JobHead AS JH
WHERE (JH.JobNo = #JobNum)
)k
where TextID = 1

SQL to get whole words till end from the keyword

Consider I have text from the field (notes) as below:
Please check http://example.com
I want a SQL query which fetches the link part only. That is to find keyword http and print till the last.
Output:
http://example.com
Also if the text field doesnt have any link, can we print NA?
CASE WHEN sys like '%Clo%'
THEN RIGHT( i.notes,LEN(i.notes) - CHARINDEX('http',i.notes,1)+1)
ELSE "No Link Available" END AS Cl_Link
For SQL Server you can consider this below logic-
DECLARE #T VARCHAR(MAX) = 'Please check http://example.com'
SELECT RIGHT(#T,LEN(#T) - CHARINDEX('http:',#T,1)+1)
For MySQL-
SET #T = 'Please check http://example.com';
SELECT RIGHT(#T,LENGTH(#T) - POSITION("http:" IN #T)+1)
In case of select query using table, queries will be-
-- SQL Server
SELECT RIGHT(column_name,LEN(column_name) - CHARINDEX('http:',column_name,1)+1) FROM your_table_name
-- MySQL
SELECT RIGHT(column_name,LENGTH(column_name) - POSITION("http:" IN column_name)+1) FROM your_table_name
To apply 'NA' when no link available, please use the below logic-
DECLARE #T VARCHAR(MAX) = 'Please check http://example.com'
SELECT
CASE
WHEN CHARINDEX('http:',#T,1) >= 1 THEN RIGHT(#T,LEN(#T) - CHARINDEX('http:',#T,1)+1)
ELSE 'NA'
END
Below is the query for your reference, executed on mysql:
SELECT substr(columnname,locate('http',columnname)) as link
FROM `tablename` where column=value
For MySQL try this:
select REGEXP_SUBSTR(text_column, 'http\:\/\/([\\w\\.\\S]+)') from mytest

MSSQL Stored Procedure with dynamically added WHERE?

I have this Stored Procedure, where i need to check if #DateChk == 1, THEN i want to add a WHERE-clause to the SQL statement in the SP. If its 0, there should not be any WHERE-clause.
How do i script such function? In a program i could just build in the string to pass to the server, but i have not found any way to do this in the SQL server.
SELECT dateDay, SUM(nok) as NOK, SUM(ok) as OK, (SUM(ok) + SUM(nok)) as 'Total'
FROM #st
SELECT CASE #DateChk
WHEN 1: WHERE dateDay BETWEEN '2016-08-01' AND '2016-08-31'
Something like this, if #DateChk = 1, the WHERE should be added, else fetch all records.
You can modify your condition like this:
SELECT dateDay, SUM(nok) as NOK, SUM(ok) as OK, (SUM(ok) + SUM(nok)) as 'Total'
FROM #st
WHERE
(#DateChk = 1 and (dateDay BETWEEN '2016-08-01' AND '2016-08-31'))
or #DateChk = 0
And it will exactly match your desired behaviour: condition on dateDay will be applied only when #DateChk = 1.

Extracting a portion of a value out of a database column using SQL server

I'm trying to extract a portion of a value out of a database column using SQL server.
The example below works in a simple context with a varchar field. The result is: &kickstart& which is what I want.
I now want to do the same when retrieving a column from the database.
But SQL does not like what I am doing. I'm thinking it is something easy that I am not seeing.
Declare #FileName varchar(20) = '&kickstart&.cfg'
Declare #StartPos integer = 0
Declare #FileNameNoExt varchar(20)
SELECT #FileNameNoExt = Left(#FileName,( (charindex('.', #FileName, 0)) - 1))
SELECT #FileNameNoExt
Here is the SQL statement that I can't seem to get to work for me:
Declare #FileNameNoExt as varchar(20)
SELECT
i.InstallFileType AS InstallFileType,
o.OSlabel AS OSLabel,
SELECT #FileNameNoExt = (LEFT(oi.FIleName,( (charindex('.', oi.FIleName, 0) ) - 1) )) AS FileNameNoExt,
oi.FIleName AS FIleName
FROM
dbo.OperatingSystemInstallFiles oi
JOIN dbo.InstallFileTypes i ON oi.InstallFileTypeId = i.InstallFileTypeId
JOIN dbo.OperatingSystems o ON oi.OperatingSystemId = o.OperatingSystemId
Why do you need the variable at all? What's wrong with:
SELECT
i.InstallFileType AS InstallFileType,
o.OSlabel AS OSLabel,
LEFT(oi.FIleName,( (charindex('.', oi.FIleName, 0) ) - 1) ) AS FileNameNoExt,
oi.FIleName AS FIleName
FROM
dbo.OperatingSystemInstallFiles oi
JOIN dbo.InstallFileTypes i ON oi.InstallFileTypeId = i.InstallFileTypeId
JOIN dbo.OperatingSystems o ON oi.OperatingSystemId = o.OperatingSystemId
You've put a SELECT inside another SELECT list without nesting, which is a syntax error in SQL Server.
You are also attempting to assign a variable while performing a data-retrieval operation. You can select all data to be shown, or all data into variables but not both at the same time.
When the two issues above are resolved, I think you may still run into issues when committing filenames into a variable which only allows 20 characters - but then I don't know anything about your dataset.

sql insert into values The multi-part identifier could not be bound

I am trying to run this command which shoulld append 80 rows.. but i get.
Msg 4104, Level 16, State 1, Line 1
The multi-part identifier "Frame.Guid" could not be bound.
INSERT INTO studentrecords(recordGuid, studentGuid, courseGuid, licenseGuid, repeatflag, frameGuid, coredata, framescore, timeinframe, locked, daterefreshed, dateinserted)
VALUES (NEWID(), '25d6e1d9-e5ce-42dd-bd6a-5956ec7cb047', '54dffd58-1af9-44cf-982e-ea0e8930878e', '00000000-1111-1111-0000-000000000000', 0, Frame.Guid, '<flags><flag1>1</flag1> <flag2>1</flag2> <flag3>1</flag3> <flag4>1</flag4> <flag5>1</flag5><flag6>1</flag6></flags><StudentAnswer> <CorrectionHistory></CorrectionHistory> </StudentAnswer>', 0, 55860, 1, GETDATE(), GETDATE())
Select Frame.Guid FROM Frame
WHERE (Frame.Course = '54dffd58-1af9-44cf-982e-ea0e8930878e') AND (Frame.Template <> '7d3a3b40-86e3-43f4-a4ca-039afdd0b7a3')
INSERT INTO studentrecords (
recordGuid, studentGuid, courseGuid, licenseGuid,
repeatflag, frameGuid, coredata,
framescore, timeinframe, locked,
daterefreshed, dateinserted
)
SELECT NEWID(),
'25d6e1d9-e5ce-42dd-bd6a-5956ec7cb047',
'54dffd58-1af9-44cf-982e-ea0e8930878e',
'00000000-1111-1111-0000-000000000000',
0, Frame.Guid, '1 1 1 1 11 ', 0, 55860, 1,
GETDATE(), GETDATE()
FROM Frame
WHERE Frame.Course = '54dffd58-1af9-44cf-982e-ea0e8930878e'
AND Frame.Template <> '7d3a3b40-86e3-43f4-a4ca-039afdd0b7a3';
I can't see how you want the "insert" and "select" queries here to be related -- they're both syntactically complete but not linked in any way. You're expecting "Frame.Guid" in the first query to come from the second query, somehow, but I can't quite get how. In any case, that's all that the error message is saying; it can't tell what you mean by Frame.Guid, exactly.
You're referencing Frame.Guid in the insert statement, but there isn't one defined. I suspect you want to select that value into a variable, then use the variable in the insert statement.
DECLARE #frameGUID GUID
SET #frameGUID = (Select Frame.Guid FROM Frame
WHERE (Frame.Course = '54dffd58-1af9-44cf-982e-ea0e8930878e')
AND (Frame.Template <> '7d3a3b40-86e3-43f4-a4ca-039afdd0b7a3'))
INSERT INTO studentrecords(recordGuid, studentGuid, courseGuid, licenseGuid, repeatflag, frameGuid, coredata, framescore, timeinframe, locked, daterefreshed, dateinserted)
VALUES (
NEWID(),
'25d6e1d9-e5ce-42dd-bd6a-5956ec7cb047',
'54dffd58-1af9-44cf-982e-ea0e8930878e',
'00000000-1111-1111-0000-000000000000',
0,
#frameGUID,
'<flags><flag1>1</flag1> <flag2>1</flag2> <flag3>1</flag3> <flag4>1</flag4> <flag5>1</flag5><flag6>1</flag6></flags><StudentAnswer> <CorrectionHistory></CorrectionHistory> </StudentAnswer>',
0,
55860,
1,
GETDATE(),
GETDATE())
You have two statements there. The INSERT statement has no way of knowing that you want the field Frame.Guid out of the SELECT statement.
You need to refactor it into one statement. You can do that by putting all the constants into the SELECT statement (between SELECT and FROM) and deleting the VALUES clause. Then it will be one statement.