How to truncate string using SQL server - sql-server

i have large string in SQL Server. I want to truncate that string to 10 or 15 character
Original string
this is test string. this is test string. this is test string. this is test string.
Desired string
this is test string. this is ......

If you only want to return a few characters of your long string, you can use:
select
left(col, 15) + '...' col
from yourtable
See SQL Fiddle with Demo.
This will return the first 15 characters of the string and then concatenates the ... to the end of it.
If you want to to make sure than strings less than 15 do not get the ... then you can use:
select
case
when len(col)>15
then left(col, 15) + '...'
else col end col
from yourtable
See SQL Fiddle with Demo

You can use
LEFT(column, length)
or
SUBSTRING(column, start index, length)

You can also use the Cast() operation :
Declare #name varchar(100);
set #name='....';
Select Cast(#name as varchar(10)) as new_name

I think the answers here are great, but I would like to add a scenario.
Several times I've wanted to take a certain amount of characters off the front of a string, without worrying about it's length. There are several ways of doing this with RIGHT() and SUBSTRING(), but they all need to know the length of the string which can sometimes slow things down.
I've use the STUFF() function instead:
SET #Result = STUFF(#Result, 1, #LengthToRemove, '')
This replaces the length of unneeded string with an empty string.

You could also use the below, the iif avoids the case statement and only adds ellipses when required (only good in SQL Server 2012 and later) and the case statement is more ANSI compliant (but more verbose)
SELECT
col, LEN(col),
col2, LEN(col2),
col3, LEN(col3) FROM (
SELECT
col,
LEFT(x.col, 15) + (IIF(len(x.col) > 15, '...', '')) AS col2,
LEFT(x.col, 15) + (CASE WHEN len(x.col) > 15 THEN '...' ELSE '' END) AS col3
from (
select 'this is a long string. One that is longer than 15 characters' as col
UNION
SELECT 'short string' AS col
UNION
SELECT 'string==15 char' AS col
UNION
SELECT NULL AS col
UNION
SELECT '' AS col
) x
) y

CASE
WHEN col IS NULL
THEN ''
ELSE SUBSTRING(col,1,15)+ '...'
END AS Col

Related

need patindex to match a-zA-Z0-9./-#' and space

I am cleaning up some data and would like to create a patindex that would reject any string contains any character(s) except for A-Za-z0-9./'-# and a space.
This rejects the special chars which should be allowed:
patindex ( '%[^A-Z0-9a-z./'-# ]%',stringtobetested )
Should I be masking the special chars? The bad and/or good chars can appear multiple times in a given string.
So where stringtobetested is abc#D-EF should pass but abc*def should fail.
This should work... it just uses replace to get around your escaping problems.
declare #stringtobetested1 varchar(64) = 'abc#D-EF'
declare #stringtobetested2 varchar(64) = 'abc*def '
select
#stringtobetested1 string1
,replace(replace(replace(replace(#stringtobetested1,'''','#'),' ','#'),'/','#'),'.','#') string1changed
,#stringtobetested2 string2
,replace(replace(replace(replace(#stringtobetested2,'''','#'),' ','#'),'/','#'),'.','#') string2changed
,patindex('%[^A-Z0-9a-z#-]%',replace(replace(replace(replace(#stringtobetested1,'''','#'),' ','#'),'/','#'),'.','#'))
,patindex('%[^A-Z0-9a-z#-]%',replace(replace(replace(replace(#stringtobetested2,'''','#'),' ','#'),'/','#'),'.','#'))
This can all be done with a PATINDEX, you just need some syntax help:
WITH test AS (
SELECT val
FROM (VALUES ('abc#D-EF./ -'''), ('abc*def')) AS t (val)
)
SELECT
input = t.val,
result = IIF(PATINDEX('%[^A-Z0-9a-z./''# -]%', t.val) > 0, 'fails', 'passes')
FROM test t;
First of all, the pattern itself is a string, and strings in T-SQL escape ' by doubling it to ''. Secondly, inside a [^ ] wildcard in a pattern, the - is used to define a character range when it occurs between two characters. By moving it to an end of the wildcard pattern, it is treated literally.
Other escape sequences specific to pattern wildcards can be found in this docs page: Pattern Matching in Search Conditions
Please run more testing for my query, and adjust max string length to fit your requirement.
DECLARE #TestString varchar(64) = 'abc#D-E/*F'
, #MaxStringLen INT = 20
;WITH cte AS(SELECT 1 number
UNION ALL
SELECT number + 1
FROM cte
WHERE number < #MaxStringLen
)
SELECT #TestString AS OriginalString
, CAST(CAST((SELECT SUBSTRING(#TestString, Number, 1)
FROM cte
WHERE Number <= LEN(#TestString) AND
SUBSTRING(#TestString, Number, 1) LIKE '%[A-Z0-9a-z-# ./'']%' FOR XML Path(''))
AS xml) AS varchar(MAX)) AS ConvertedString
, CASE WHEN #TestString = CAST(CAST((SELECT SUBSTRING(#TestString, Number, 1)
FROM cte
WHERE Number <= LEN(#TestString) AND
SUBSTRING(#TestString, Number, 1) LIKE '%[A-Z0-9a-z-# ./'']%' FOR XML Path(''))
AS xml) AS varchar(MAX))
THEN 1 ELSE 0 END IsAllowed

select from SQL table with concatenation of two string columns

Issue
I want to write a query that will select all from a table where my string value is equal to two columns concatenated together.
This is plain English version:
#MYSTRING varchar(50)
SELECT ALL FROM [FFLOCNP] WHERE COLUMN1 + COLUMN2 = #MYSTRING
I have tried to use the COALESCE but i have never used this before and it is returning me an error:
#CODE varchar(50)
SELECT * FROM [dbo].[FFLOCNP] WHERE COALESCE([LOCTRY], '') || COALESCE([LOCLCN], '') = #CODE
you have to use ISNULL for this.
Use below query may be it helps you.
SELECT * FROM [FFLOCNP] WHERE ISNULL(COLUMN1,'') + ISNULL(COLUMN2,'') = #MYSTRING
Be careful, when using ISNULL instead of COALESCE. ISNULL limits the returned value to the datatype of the first input parameter. In the given example column V1 will be implicitly defined with nvarchar(1), because the longest text in column V1 consists of only one character. ISNULL(V1, [param2]) will therefor return always a one character long string, regardless of the length of the second parameter. In your case ISNULL would work, if you wanted to replace a NULL with an empty string. If you wanted to replace a NULL with a longer string then you MUST use COALESCE instead of ISNULL. COALESCE returns the full string in parameter 2 regardless of the datatype of parameter 1. Apart from this COALESCE is standard SQL whereas ISNULL is a flavor of SQL-Server. Standard SQL should be preferred to T-SQL flavor to get more portable code.
WITH CTE_SRC AS
(
SELECT
[V1]
,[V2]
FROM
(VALUES
(N'A', N'BB')
,(NULL, N'BB')
,(N'A', NULL)
) T([V1],[V2])
)
SELECT
ISNULL([V1], '1234') AS [ISNULL]
,COALESCE([V1], '123') AS [COALESCE]
FROM
CTE_SRC
Result
ISNULL COALESCE
------ --------
A A
1 123
A A

SQL: Filter on Alpha and numeric on column of Type TEXT

I've got a column of type Text. In the column are numeric values such as4, 8, 3.2, etc... and also values such as 'Negative', 'Positive', '27A', '2pos 1neg'.
The user needs to be able to say: "Give me all the values between 10 and 30, and also the values that are 'Negative'. The WHERE clause would need to do something along the lines of:
WHERE Tbl.Col > 10
AND Tbl.Col < 30
AND Tbl.Col = 'Negative'
This is problematic for obvious reasons. I've tried using the ISNUMERIC function to alleviate the issue but can't seem to get exactly what i need. I can either get all the alpha values in the column, or all the numeric values in the column as floats but cant seem to filter on both at the same time. To grab all the Numeric values I've been using this:
SELECT Num.Val FROM
(SELECT Val = CASE ISNUMERIC(CAST(TBL.COL AS VARCHAR)) WHEN 1
THEN CAST(CAST(TBL.COL AS VARCHAR) AS FLOAT) ELSE NULL END
FROM Table TBL
WHERE TBL.COL IS NOT NULL ) as Num
WHERE Num.val IS NOT NULL
AND Num.val > 10
If I understand the issue correctly something like this should get you close.
with MyNumbers as
(
select t.Col
from Tbl t
--where ISNUMERIC(t.Col) = 1
where t.Col NOT LIKE '%[^0-9.]%'
)
, MyAlpha as
(
select t.Col
from Tbl t
where ISNUMERIC(t.Col) = 0
)
select Col
from MyNumbers
where Col > 10
and Col < 30
union all
select Col
from MyAlpha
where ColorMatch = ' Negative'
First I would go slap the person who designed the table (hopefully it isn't you) :>
Go to here and get the split table function. I would then convert the text column (like you have in example above) into varchar(max) and supply it as the parameter to the split function. Then you could select from the table results of the split function using the user supplied parameters.
I have found the answer to my problem:
SELECT
al_Value = Table.Column
FROM Table
WHERE (
ISNUMERIC(CAST(Table.Column AS VARCHAR)) = 1 AND
CONVERT(FLOAT, CAST(Table.Column AS VARCHAR)) > 1.0 AND
CONVERT(FLOAT, CAST(Table.Column AS VARCHAR)) < 10.0
)
OR (
CAST(Table.Column AS VARCHAR) IN ('negative', 'no bueno')
)
This will return one column named 'al_Value' that filters on Table.Column (which is of Datatype TEXT) and apply the filters in the WHERE clause above.
Thanks everyone for trying to help me with this issue.

SQL Server casting from a table

In SQL Server I have a query that looks like this (part of the WHERE clause of a larger query)
SELECT 1
WHERE TPR.GRDE_PK IN
(
SELECT CAST(String AS INT)
FROM dbo.Split_New(#GRADES, ',')
)
#Grades is equal to '14,15' and dbo.Split_New is a function that returns a table with a single column called String that will contains '14' and '15'. TPR.GRDE_PK is of type INT. I get a conversion error when I try to execute this line, can anyone tell me how to fix it?
Here is that the Split_New function looks like (Written by someone more skilled than me, so I don't understand all of it):
function [dbo].[Split_New] (
#StringToSplit nvarchar(4000),
#Separator varchar(128))
returns table as return
with indices as
(
select 0 S, 1 E
union all
select E, charindex(#Separator, #StringToSplit, E) + len(#Separator)
from indices
where E > S
)
select substring(#StringToSplit,S,
case when E > len(#Separator) then e-s-len(#Separator) else len(#StringToSplit) - s + 1 end) String
--,S StartIndex
from indices where S >0
The problem is your TPR.GRDE_PK value is an Integer, cast it as a VARCHAR():
SELECT 1
WHERE CAST(TPR.GRDE_PK AS VARCHAR(25)) IN
(
SELECT *
FROM dbo.Split_New(#GRADES, ',')
)
The function works fine, it returns the expected table of results given your string.
Alternatively, you can avoid using the function at all with LIKE:
WHERE ','+CAST(TPR.GRDE_PK AS VARCHAR(25))+',' LIKE '%,'+#GRADES+',%'
It is difficult to say exactly what it is without looking at the function.
First see if you get the correct results from the function:
SELECT String FROM dbo.Split_New(#GRADES, ',')
String may have leading/trailing spaces. Try to trim them before converting/casting using LTRIM() and RTRIM() function
SELECT CONVERT(INT, LTRIM(RTRIM(String))) FROM dbo.Split_New(#GRADES, ',')
ISNUMERIC() function is not ideal to filter and convert as it returns 1 for some characters that are not numbers.

SQL Server converting a variable varchar field to money/decimal/something with decimal places

I'm looking for an elegant way to convert a field of type varchar, with variable data in it, to a data type which can be used for mathematical operations sample data from the field
(excluding quotes)
''
'abc'
'23'
'23.2'
The method should work for all, and for the first & second values should return 0, and not throw an SQL Server error..
Try this:
SELECT CASE WHEN IsNumeric(YourColumn) = 0 THEN
0
ELSE
CAST(YourColumn AS decimal(18, 2))
END
You have to adjust the destination data type, I have chosen decimal(18, 2) for demonstration.
I know this is a long-dead thread, but I recently stumbled upon it from a Google search and had a thought. It is less elegant than a CASE statement, but it is an alternative.
SELECT
COALESCE(CAST(NULLIF(ISNUMERIC(LEFT(MyColumn, PATINDEX('% %', MyColumn + ' ') - 1)), 1) AS MONEY), LEFT(MyColumn, PATINDEX('% %', MyColumn + ' ') - 1))
FROM
myTable
or you could do:
Select COALESCE(CAST(NULLIF(ISNUMERIC(MyColumn), 1) AS MONEY), MyColumn)
FROM
myTable
The top version would see "2 5" as just 2, the bottom one would see it as a text field.
SELECT CASE IsNumeric(mycol) WHEN 1 THEN CAST(mycol AS FLOAT) ELSE 0 END
FROM mytable
If you'd like to convert it, you should use UPDATE instead of SELECT
UPDATE Table
SET Col1 = CAST(Col1 As Decimal(18,2))
COALESCE is a great option for this: Find more information here. It evaluates the arguments in order and returns the current value of the first expression that initially does not evaluate to NULL.
ISNUMERIC returns 0 or 1 depending on if the value being evaluated could be considered one of the SQL 'number' or 'numeric' types. e.g. int, bigint, money..
NULLIF essentially finds the value you specify and if it matches it replaces it with a NULL value.
CAST Simply changes a data type to another in this example to MONEY
As you can see, if you break the below down using this information its quite an elegant solution I think?
COALESCE(CAST(NULLIF(ISNUMERIC(COL1), 1) AS MONEY), COL1)

Resources