Split values in an variable in SQL Server 2005 - sql-server

I have a varchar variable been defined like this.
declare #IDs varchar(50)
set #IDs ='111,123,567,'
Now I need to extract the last value in the list always 567.
The values in #IDs can be like this also
set #IDs ='56,'
In this case we need extract only the value 56.
How can we do it?

i think you will find this user defined function to split the string helpful:
http://www.codeproject.com/Articles/7938/SQL-User-Defined-Function-to-Parse-a-Delimited-Str

You can use the string splitter found here: http://www.sqlservercentral.com/articles/Tally+Table/72993/
It is very fast, you can call it like so:
SELECT *
FROM dbo.DelimitedSplit8K(#IDs,',')
This will return you a result set of all the values in the string.

Related

NVARCHAR SQL type problem with Persian char

I have a problem in SQL with NVARCHAR type and Persian char 'ی' and 'ک', I have some records in a Table like:
+----- Name ------+
+----- علی ------+
When I want to select from this Table like:
select * from [Table] when Name like 'علی'
select * from [Table] when Name='علی'
select * from [Table] when Name like 'علي'
select * from [Table] when Name='علي'
It returns NULL! I found that when I use N before strings it is solved but I need to use N before parameter in SP and try this:
declare #name nvarchar(max)='علی'
select * from [Table] when Name like N''+#name
But unfortunately it is not working and I found when I assign 'علی' to the nvarchar, automatically 'ی' converted to 'ي'!!!
How can I fix that?
It seems like you're using MS SQL Server. In that case the N prefix denotes a unicode string.
Thus, you should use N'*' whenever you set a unicode string. Therefore, you should change your stored procedure like so:
declare #name nvarchar(max)=N'علی'
select * from [Table] when Name like #name
1- Search and find the best Collation and Unicode for your database. It can be different in each case.
2- If you are using a programming language, you can handle it there. When you want to save a record, you should change ی ک ه and unify them. It means you should always use the same char. In save, update and select(in where clause).
3- You can make a trigger for Insert and unify characters.
You don't need to use N before a parameter that is Nvarchar.
This will work :
declare #name nvarchar(max)='علی' -- or maybe you want '%علی%'
select * from [Table] when Name like #name

Get only numeric part of a column data?

I have a column in my database containing both numeric and alphanumeric characters.
I only want to get the numeric (6 numbers) from the column.
Example of data:
TEST_123456_Prod
DB111111P
F222222FN
PROD999999_SCF
I want to create a select statement that returns all rows from this column where all but numbers are filtered out.
I´m using SQL Server, so probably Charindex needs to be used, but no idea how.
To strip off all alphanumeric characters you can create a function as:
CREATE FUNCTION [dbo].[RemoveAlphaCharacters](#InputString VARCHAR(1000))
RETURNS VARCHAR(1000)
AS
BEGIN
WHILE PATINDEX('%[^0-9]%',#InputString)>0
SET #InputString = STUFF(#InputString,PATINDEX('%[^0-9]%',#InputString),1,'')
RETURN #InputString
END
GO
and then use it to get desired result as:
select dbo.RemoveAlphaCharacters(databasename)
from T1;
SQL Fiddle
This will work for all of your examples:
SELECT
SUBSTRING(databasename,
PATINDEX('%[0-9]%', databasename),
LEN(databasename) - (PATINDEX('%[0-9]%', REVERSE(databasename)) + PATINDEX('%[0-9]%', databasename)) + 2)
FROM dbs
Here is a SQLFiddle with how the code works.

Add "-" to varchar value in SQL Server

I have a TELEPHONE_NUMBER as a varchar like this:
Value : "1112223344"
And I need to add "-" to the value like this:
111-222-33-44
So how can I add - to my telephone number value in my SQL Server stored procedure?
CREATE PROCEDURE SP_TELEPHONE_NUMBER
(#TELEPHONE_NUMBER VARCHAR(4000))
AS
BEGIN
INSERT INTO DOSYA_ARSIV(TELEPHONE_NUMBER)
VALUES(#TELEPHONE_NUMBER)
END
Just an alternative:
select SUBSTRING('1112223344',1,3)+'-'+
SUBSTRING('1112223344',4,3)+'-'+
SUBSTRING('1112223344',7,2)+'-'+
SUBSTRING('1112223344',9,2)
In your case:
CREATE PROCEDURE SP_TELEPHONE_NUMBER
(#TELEPHONE_NUMBER VARCHAR(4000))
AS
BEGIN
INSERT INTO DOSYA_ARSIV(TELEPHONE_NUMBER)
VALUES
(
SUBSTRING(#TELEPHONE_NUMBER,1,3)+'-'+
SUBSTRING(#TELEPHONE_NUMBER,4,3)+'-'+
SUBSTRING(#TELEPHONE_NUMBER,7,2)+'-'+
SUBSTRING(#TELEPHONE_NUMBER,9,2)
)
END
As noobob has mentioned in his comment, you may have this as an INT type (INT,BIGINT or something similar) and just handle the way it is displayed in the front end. For instance in C# you would have it as:
TELEPHONE_NUMBER.ToString("###-###-##-##");
Another comment would be that defining the expected argument as VARCHAR(4000) is way too much. Though it might not be very bad, it is a good point to define arguments or variables as close to expected input as you can. In your case i would say that something like VARCHAR(30) would be enough.
Use STUFF function in the MS SQL server
SET #TELEPHONE_NUMBER=STUFF(STUFF(STUFF(#TELEPHONE_NUMBER,4,0,'-'),8,0,'-'),11,0,'-')

Problem with comma in insert statement

Am facing problem while inserting data into sqlserver using query in c# as
Insert into table1(sid,sname) values(1,'ram,rahim,robert')
Are you using quotes around the variable in the command string? Try using the command without quotes.
command.text=string.Format("insert into table(sid,sname) values(1,#data)");
String or binary data would be truncated is an error indicating that you are trying to store a string that is longer than the field in the database.
use like
insert into table1(sid,sname,column3,column4) values(1,'ram','rahim','robert')
But you have to add four columns.Now you have only two sid and sname. Add another two columns.
declare #str varchar(200)
set #str = 'ram,rahim,robert';
Insert into table1(sid,sname) values(1,#str )

Getting at string data in SQL

I have a row entry with the following format:
Site=[number];this=that;foo=bar;
[number] above can be from 1...infinity. So I need to split out the [number] to use in another select statements where clause. Site=[number] is always at the beginning in the string and the data is always separated by a semi-colon.
declare #t nvarchar(100) = 'Site=230;this=that;foo=bar;';
select convert(int, substring(#t,6, charindex(';',#t,0)-6))
SELECT SUBSTRING(col, 1, CHARINDEX(col,';'))
Why are you storing data in the database in this format? Split it up into columns so that you can do meaningful queries.
You can play with the string this way:
declare #tx as nvarchar(100)
set #tx = 'Site=[number];this=that;foo=bar;'
print substring(
#tx,
CHARINDEX('[', #tx)+1,
CHARINDEX(']',#tx)-CHARINDEX('[',#tx)-1)
Hope this helps.
I don't have MS Sql Server available to try this out, but have you tried something like
Select
field
convert(bigint, substring(field, 6)) as thenum
from
thetable
where
condition=something
where field is the name of the field containing site=[number];...
The theory goes that substring will strip off site= off the beginning, and convert
will (hopefully) convert the number portion and ignore the rest of the text from the semicolon onwards.
It may or may not work. If not you may need to write an elaborate function instead.

Resources