I am trying to concatenate strings but it doesn't seem to work. Can somebody tell me what is wrong with the code below?
declare #x varchar = 'a';
SET #x += 's'
SET #x = #x + 'z'
SET #x = concat('x','y')
SELECT #x;
None of the above methods worked. I am getting the output as 'x'.
As per Aaron Bertrand's article here:
https://sqlblog.org/2009/10/09/bad-habits-to-kick-declaring-varchar-without-length
...you should not be declaring VARCHAR without a length.
The problem is, if you don't define a length, SQL Server will assign
one for you, and it may not be as wide as you expect. In some
scenarios, it will be 1 (yes, that is the number one, not a typo), and
in others it will be 30.
The docs are quite clear in this as well:
varchar [ ( n | max ) ]
When n is not specified in a data definition or variable declaration
statement, the default length is 1. When n is not specified when using
the CAST and CONVERT functions, the default length is 30.
This will work fine:
declare #x varchar(10) = 'a';
SET #x += 's'
SET #x = #x + 'z'
SET #x = concat('x','y')
SELECT #x;
You need a length when you declare varchar(). Otherwise, it is only one character long:
declare #x varchar(255) = 'a';
Once the variable is big enough to store the value, the rest of the code should work.
You need to tell sql the length of your varchar. In most cases sql treat varchar as varchar(1)
declare #x varchar(10) = 'a';
SET #x += 's'
SET #x = #x + 'z'
SET #x = concat('x','y')
SELECT #x;
You need to declare your VARCHAR with a length, try changing it to VARCHAR(20) and see what happens.
Declaring VARCHAR without a length results in Length being 1.
The code below will work, remember you need to declare strings long enough to contain the result.
declare #a varchar(100)
declare #b varchar(100)
set #a = 'This should ';
set #b = 'work';
select #a + #b
If you have shorter strings like this:
declare #a varchar(4)
declare #b varchar(4)
set #a = 'This should ';
set #b = 'work';
select #a + #b
You'll end up with the result:
'Thiswork'
Related
I had to write a SP to generate a string with the combination of Country (7 chars) + Province (1 char) + numeric number starts from 01. for eg: JAMAICAK01
where JAMAICA (Country) , K (Province) and 01 is the numeric number that gets incremented by 1 for each transaction.
The issue I have here is the generated string length max is 10, can be lesser than 10 but not >10.
It should be handled in a way with certain rules like
the combination don't exist
When the numeric unit changes from tens to hundreds making the string
length >10, I need to remove the right chars for eg JAMAICAKKK10 to
JAMAICAK10 from the right to make the total max length 10.
In my code below I tried to check if the combination exists and I get the max of it and do the numeric increment from the last one. think it can be done in a better way.
Declare #Province char(2)
Declare #Country varchar(10)
declare #CounProv varchar(10)
Declare #SimilarCounPRov varchar(max) = '';
declare #FinalString nvarchar(12)
declare #s varchar(50)
declare #s1 varchar(50)
declare #s2 varchar(50)
Set #Province = LEFT('KINGSTON', 1)
Set #Country = LEFT('JAMAICA', 7)
Set #CounProv = #Country+#Province
Select #SimilarCounPRov = MAX(field1) from dbo.table where field1
LIKE '%JAMAICAK%'
if #SimilarCounPRov IS NOT NULL
BEGIN
Set #s = (select fn_AlphaOnly('%JAMAICAK99%')) -- returns JAMAICAK
Set #s1 = (select fn_NumericOnly('%JAMAICAK99%')) -- returns 199
set #s2= #s1 +1 -- increment by 1
if len(#FinalString) > 10
----
need help here----`
I'm not sure that I understood all your requirements but if you need to generate strings like : JAMAICAK1,JAMAICAK2,...JAMAICAK10...,JAMAICAK11,...JAMAICA100,JAMAICA101,...JAMAIC1000,JAMAIC1001...
You can try to exploit this piece of code :
Declare #Province char(2)
Declare #Country varchar(10)
Declare #CounProv varchar(10)
Declare #value int
Declare #str_value VARCHAR(100)
Set #Province = LEFT('KINGSTON', 1)
Set #Country = LEFT('JAMAICA', 7)
Set #value = 999999
Set #CounProv = #Country+#Province
Set #str_value = (select CAST(#value AS varchar(100)))
select LEFT(#CounProv,10-LEN(#str_value))+#str_value
Tell me if it helps.
I've declared a variable in a stored procedure:
DECLARE #CurrentChunk NVARCHAR(250)
I would like to use the length of the variable, i.e. 250, later in my sp for computational purposes, and I want to keep my code as dry as possible.
Here's my code (assume #Narrative is a param to the SP):
DECLARE #ChunkSizeCharacters INT,
#NumChunks INT,
#LoopIndex INT,
#CurrentChunk NVARCHAR(250)
SET #ChunkSizeCharacters = 250 -- HERE'S WHERE I WANT THE LENGTH OF #CurrentChunk
SET #NumChunks = CEILING((LEN(#Narrative) * 1.0)/#ChunkSizeCharacters)
SET #LoopIndex = 0;
WHILE (#LoopIndex < #NumChunks)
BEGIN
SET #CurrentChunk = SUBSTRING(#Narrative,
((#LoopIndex * #ChunkSizeCharacters) + 1), #ChunkSizeCharacters)
INSERT INTO [dbo].[Chunks] ([Chunk]) VALUES (#CurrentChunk)
SET #LoopIndex = #LoopIndex + 1
END
Is there a way to ascertain the length of an NVARCHAR or VARCHAR variable definition (please read carefully -- I'm not looking for LEN())?
It seems the MaxLength variant property returns the value you're looking for.
DECLARE #Banana varchar(255) = 'This banana'
SELECT SQL_VARIANT_PROPERTY(#Banana, 'MaxLength')
Returns 255.
If you don't mind overwriting the variable (and if you do, you can assign it to a temp NVARCHAR(MAX)):
SELECT #CurrentChunk = REPLICATE(0, 8000);
SELECT #ChunkSizeCharacters = LEN(#CurrentChunk);
This trick does not and cannot work for NVARCHAR(MAX), but that's presumably no problem, given it's enormous maximum size.
Unfortunately T-SQL has nothing in the way of metadata properties for variables. Even determining the type of an expression is a chore.
Interestingly, the value returned by that SELECT SQL_VARIANT_PROPERTY statement doesn't select into a plain, predefined variable. In the end, I used:
DECLARE #Text VARCHAR(400), #TextLen INT
SELECT #TextLen = CAST(SQL_VARIANT_PROPERTY(ISNULL(#Text, ''), 'MaxLength') AS INT)
Works like a charm for me!
This might be a very simple select statement, here's my question.
I have a variable
DECLARE #A varchar(128) --declaring variable
SET #A = 'sus_123456_R5_20140506' --setting value
I want to find the value after 'sus_' and before 'R5'
Also, the value in between is not of fixed length. So the function has to be dynamic.
However it always have sus and _R5_date. That's constant.
SET #A = 'sus_129_R5_20150408
Thanks
Use SUBSTRING in combination with CHARINDEX:
SELECT SUBSTRING(#A,CHARINDEX('sus_',#A,0)+4,CHARINDEX('_R5',#A,0)-5)
You can try this once using SUBSTRING() and CHARINDEX() FUNCTION
DECLARE #A varchar(128) --declaring variable
SET #A = 'sus_123456_R5_20140506'
select substring(#A,charindex('_',#A)+1,charindex('r5',#A)- (2+charindex('_',#A)))
Results in: 123456
(OR) This one using LEFT(),RIGHT() and CHARINDEX() function.
DECLARE #A varchar(128)
SET #A = 'sus_129_R5_20150408'
select right(left(#A,charindex('R5',#A) - 2),charindex('_',#A) - 1)
Results in: 129
Read more about String Function
Is there MS SQL Server function that counts the number of times a particular character appears in a string?
There's no direct function for this, but you can do it with a replace:
declare #myvar varchar(20)
set #myvar = 'Hello World'
select len(#myvar) - len(replace(#myvar,'o',''))
Basically this tells you how many chars were removed, and therefore how many instances of it there were.
Extra:
The above can be extended to count the occurences of a multi-char string by dividing by the length of the string being searched for. For example:
declare #myvar varchar(max), #tocount varchar(20)
set #myvar = 'Hello World, Hello World'
set #tocount = 'lo'
select (len(#myvar) - len(replace(#myvar,#tocount,''))) / LEN(#tocount)
Look at the length of the string after replacing the sequence
declare #s varchar(10) = 'aabaacaa'
select len(#s) - len(replace(#s, 'a', ''))
>>6
You can do that using replace and len.
Count number of x characters in str:
len(str) - len(replace(str, 'x', ''))
Use this function begining from SQL SERVER 2016
Select Count(value) From STRING_SPLIT('AAA AAA AAA',' ');
-- Output : 3
When This function used with count function it gives you how many
character exists in string
try that :
declare #t nvarchar(max)
set #t='aaaa'
select len(#t)-len(replace(#t,'a',''))
You can do it inline, but you have to be careful with spaces in the column data. Better to use datalength()
SELECT
ColName,
DATALENGTH(ColName) -
DATALENGTH(REPLACE(Col, 'A', '')) AS NumberOfLetterA
FROM ColName;
-OR-
Do the replace with 2 characters
SELECT
ColName,
-LEN(ColName)
+LEN(REPLACE(Col, 'A', '><')) AS NumberOfLetterA
FROM ColName;
function for sql server:
CREATE function NTSGetCinC(#Cadena nvarchar(4000), #UnChar nvarchar(100))
Returns int
as
begin
declare #t1 int
declare #t2 int
declare #t3 int
set #t1 = len(#Cadena)
set #t2 = len(replace(#Cadena,#UnChar,''))
set #t3 = len(#UnChar)
return (#t1 - #t2) / #t3
end
Code for visual basic and others:
Public Function NTSCuentaChars(Texto As String, CharAContar As String) As Long
NTSCuentaChars = (Len(Texto) - Len(Replace(Texto, CharAContar, ""))) / Len(CharAContar)
End Function
It will count occurrences of a specific character
DECLARE #char NVARCHAR(50);
DECLARE #counter INT = 0;
DECLARE #i INT = 1;
DECLARE #search NVARCHAR(10) = 'o'
SET #char = N'Hello World';
WHILE #i <= LEN(#char)
BEGIN
IF SUBSTRING(#char, #i, 1) = #search
SET #counter += 1;
SET #i += 1;
END;
SELECT #counter;
Use this code, it is working perfectly.
I have create a sql function that accept two parameters, the first param is the long string that we want to search into it,and it can accept string length up to 1500 character(of course you can extend it or even change it to text datatype).
And the second parameter is the substring that we want to calculate the number of its occurance(its length is up to 200 character, of course you can change it to what your need). and the output is an integer, represent the number of frequency.....enjoy it.
CREATE FUNCTION [dbo].[GetSubstringCount]
(
#InputString nvarchar(1500),
#SubString NVARCHAR(200)
)
RETURNS int
AS
BEGIN
declare #K int , #StrLen int , #Count int , #SubStrLen int
set #SubStrLen = (select len(#SubString))
set #Count = 0
Set #k = 1
set #StrLen =(select len(#InputString))
While #K <= #StrLen
Begin
if ((select substring(#InputString, #K, #SubStrLen)) = #SubString)
begin
if ((select CHARINDEX(#SubString ,#InputString)) > 0)
begin
set #Count = #Count +1
end
end
Set #K=#k+1
end
return #Count
end
What mistake I am making in this sql query
Declare #str Varchar(100) = 'asasa,bsasas,csasa,dsczxvvc'
declare #d varchar(2)=','
SELECT
RIGHT(LEFT(#str,Number-1),
CHARINDEX(#d,REVERSE(LEFT(#d+#str,Number-1))))
FROM
master..spt_values
WHERE
Type = 'P' AND Number BETWEEN 1 AND LEN(#str)
AND SUBSTRING(#str,Number,1) = #d
Expected Result
(No column name)
asasa
bsasas
csasa
dsczxvvc
Actual Result
(No column name)
asasa
bsasas
csasa
Your AND SUBSTRING(#str, Number, 1) = #d is forcing a comma to be at the end of dsczxvvc...there isn't one. asasa,bsasas,csasa,dsczxvvc, works.
add one more comma at the end of string
you can directly add comma in the string like = "asasa,bsasas,csasa,dsczxvvc,"
or
handle this thing in sql side.
Declare #str Varchar(100)
set #str = 'asasa,bsasas,csasa,dsczxvvc'
declare #d varchar(2)
set #d =','
set #str = #str + ','
SELECT
RIGHT(LEFT(#str,Number-1),
CHARINDEX(#d,REVERSE(LEFT(#d+#str,Number-1))))
FROM
master..spt_values
WHERE
Type = 'P' AND Number BETWEEN 1 AND LEN(#str)
AND SUBSTRING(#str,Number,1) = #d
This is because since the last string portion does not have the seperator at the end of the string
If you add the following code just before the SELECT statement, it will work
set #str = #str + #d
There are many split functions on the web, you can use one of them actually.
Split string using CLR function
Split using XML
SQL Server split string function