SQL Server - Parsing an input string -- help please
Asked By Burak Gunay
19-Dec-06 02:42 PM
Hello,
I want to pass in to my procedure an input string with values delimited by a semicolon
'100;200;300;400;'
and I want to parse this string and use the individual values in an insert statement loop within a transaction.
How can I do this?
Thanks,
Burak
try custom split function
refer the links
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=50648
http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=653&lngWId=5
Sushila Patel replied to Burak Gunay
Check out the Sample "Parse a comma delimited comma.."
http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=1110&lngWId=5
http://www.codeproject.com/database/SQL_UDF_to_Parse_a_String.asp
http://www.planetsourcecode.com/vb/scripts/ShowCode.asp?txtCodeId=1110&lngWId=5
ok, then what?
hello,
i'm going to use the split function in
http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=653&lngWId=5
how do i store the returned strings in my stored procedure after i call the split function?
thanks,
burak
thanks.. need some more help
hello,
i'm going to use the split function in
http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=653&lngWId=5
how do i store the returned strings in my stored procedure after i call the split function? how do i use these values ina transaction loop.
thanks,
burak
Split function in your database
will take the entire delimited string and return a table that you can program against:
CREATE FUNCTION [dbo].[fn_Split](@text varchar(8000), @delimiter varchar(20) = ' ')
RETURNS @Strings TABLE
(
position int IDENTITY PRIMARY KEY,
value varchar(8000)
)
AS
BEGIN
DECLARE @index int
SET @index = -1
WHILE (LEN(@text) > 0)
BEGIN
SET @index = CHARINDEX(@delimiter , @text)
IF (@index = 0) AND (LEN(@text) > 0)
BEGIN
INSERT INTO @Strings VALUES (@text)
BREAK
END
IF (@index > 1)
BEGIN
INSERT INTO @Strings VALUES (LEFT(@text, @index - 1))
SET @text = RIGHT(@text, (LEN(@text) - @index))
END
ELSE
SET @text = RIGHT(@text, (LEN(@text) - @index))
END
RETURN
END
-- Example usage in a stored proc, to insert into Table variable:
/*
DECLARE @WORDS TABLE
(
ID INT IDENTITY (1,1),
string varchar(100)
)
INSERT INTO @WORDS
SELECT VALUE AS WORD FROM dbo.fn_Split( @WordsToInsert,' ')
*/
thanks ,, and a quick question

Peter,
I wrote a stored procedure using your function and it works fine. I was wondering how I could make the while statement at the end more elegant and add transaction functionality into it?
CREATE PROCEDURE dbo.wsp_Roles_AssignSchoolsByUserId
@UserId uniqueidentifier,
@Schools varchar(8000)
AS
-- declare a table to hold school names
DECLARE @USER_SCHOOLS TABLE
(
ID INT IDENTITY (1,1),
SCHOOL char(4)
)
-- parse the delimited list of schools into individual schools
-- and insert the school names into the user_schools table
INSERT INTO @USER_SCHOOLS
SELECT VALUE AS SCHOOL FROM dbo.fn_Split( @Schools,';')
-- check to see if table has any records
DECLARE @COUNT int
SELECT @COUNT = count(*) FROM @USER_SCHOOLS
IF @COUNT > 0
BEGIN
-- select individual school names and insert them along with the user id
-- into tbl_UsersInSchools
DECLARE @SCHOOL char(4)
WHILE( @COUNT > 0 )
BEGIN
SET @SCHOOL = (SELECT TOP 1 SCHOOL from @USER_SCHOOLS)
INSERT INTO tbl_UsersInSchools VALUES (@UserId, @SCHOOL)
DELETE FROM @USER_SCHOOLS WHERE SCHOOL = @SCHOOL
SET @COUNT = @COUNT - 1
END
END
GO
alternative solution
Here is some SQL code which might be useful for you, you can customize it as per your requirements. This does not use a table variable so should have a faster run time.
declare @school varchar(8000)
declare @pos1 int
declare @pos2 int
declare @err_code INT
set @pos1 = 1
set @pos2 = 1
set @school = '1232;23;45;56;746;'
set @pos2 = charindex(';',@school)
while (@pos1<@pos2)
begin
begin transaction
print substring(@school,@pos1,@pos2-@pos1)
-- Insert statement
if (@@Error>0)
begin
@err_code = @@Error
end
-- Update Statement
if (@@Error>0)
begin
@err_code = @@Error
end
-- Delete statement
if (@@Error>0)
begin
@err_code = @@Error
end
commit transaction
if(@err_code>0)
begin
PRINT 'Unexpected error occurred!' + STR(@err_code)
Rollback transaction
end
set @pos1 = @pos2 + 1
set @pos2 = @pos2+charindex(';',substring(@school,@pos1,len(@school)- @pos1+1))
end
Hope this helps.

sqlhelper class Hi This the sql helper class, when i use it i got cmd error.wt is the soltion using System; using System.Data; using System.Xml; using System.Data case than an intended pure output parameter (derived as InputOutput) / / / where the user provided no input value. / / / < / summary> / / / <param name = "command"> The command to which the parameters will be added< / param derived output value with no value assigned if ( ( p.Direction = = ParameterDirection.InputOutput | | p.Direction = = ParameterDirection.Input ) && (p.Value = = null)) { p.Value = DBNull.Value; } command.Parameters.Add(p); } } } } / / / <summary> / / / This method assigns SqlParameters to be assigned values< / param> / / / <param name = "dataRow"> The dataRow used to hold the stored procedure's parameter values< / param> private static void AssignParameterValues(SqlParameter[] commandParameters, DataRow dataRow) { if ((commandParameters = = null Check the parameter name if( commandParameter.ParameterName = = null | | commandParameter.ParameterName.Length < = 1 ) throw new Exception( string.Format( "Please provide a valid parameter name on the parameter #{0}, the ParameterName property has param> / / / <param name = "transaction"> A valid SqlTransaction, or 'null'< / param> / / / <param name = "commandType"> The CommandType (stored procedure, text, etc.)< / param> / / / <param name = "commandText"> The stored procedure name or T-SQL command
Any one send frequently asked Important questions in C# .Net, ADO .Net, Asp .Net and Sql Server. . . . . . . . tx in Advance. . . . . . Hi, Find this. . (B)What is an IL? (B)What is a how do you go about it? (A) What is Manifest? (B) Where is version information stored of an assembly? (I) Is versioning applicable to private assemblies? (B) What is GAC? (I objects in Remoting? (A) What are the ways in which client can create object on server in CAO model? (A) Are CAO stateful in nature? (A) To create objects in CAO Hidden frames? (I) What are benefits and limitations of using Cookies? (I) What is Query String and What are benefits and limitations of using Query Strings? (I) What is Absolute and page ? (I) Can we post and access view state in another application? (I) What is SQL Cache Dependency in ASP.NET 2.0? (I) How do we enable SQL Cache Dependency in ASP.NET 2.0? (I) What is Post Cache substitution? (I) Why C#? (A)Can two catch blocks be executed? (A) What is the difference between System.String and System.StringBuilder classes? Chapter 7: ASP.NET (B) What’ is the sequence in which
choosen the Blog post from here This means the installation should be on a single server as Domain Controller , as MS SQL database server and as MOSS2007 server farm. Only one uses should be used. Thats what I have done, I followed the I am reading the logfiles placed under "c: \ program files \ common files \ microsoft shared \ web server extensions \ 12 \ logs". I don't find any relavant information regarding authentication or what else High . . .g newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject) bei System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart) bei System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) bei System.Data.SqlClient.SqlInternalConnectionTds. . ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo
Hi, I have a SSAS project I want to deploy it. But There is an error like Error :The project could not be deployed to the 'localhost' server because of the following connectivity problems : A connection cannot be made. Ensure that the server is running. To verify or update the name of the target server, right-click on the project in Solution Explorer, select Project Properties, click on the Deployment tab, and then enter the name of the server. i m not able to deploy. Plz tell me wht are the configuration of this http: / / msdn.microsoft.com / en-us / library / ms175672.aspx For cube building, you can use SQL Server 2000 Analysis Services, SQL Server 2005 Analysis Services, or SQL Server 2008 Analysis Services. This
to this other are not processing. and am getting below one in log file as error cause: Microsoft Windows Installer 4.5 Update (x86) - Windows XP: [2] CGenericComponent::Install() expects the attempted to be installed. [08 / 10 / 11, 14:26:01] VS70pgui: [2] DepCheck indicates Microsoft SQL Server Compact 3.5 SP2 (x86) ENU was not attempted to be installed. [08 / 10 / 11, 14:26:01] VS70pgui: [2] DepCheck indicates Visual Studio 2010 Tools for SQL Server Compact 3.5 SP2 ENU was not attempted to be installed. [08 / 10 / 11, 14 attempted to be installed. [08 / 10 / 11, 14:26:02] VS70pgui: [2] DepCheck indicates Microsoft SQL Publishing Wizard 1.4 was not attempted to be installed. [08 / 10 / 11, 14:26:02] VS70pgui: [2] DepCheck indicates Microsoft SQL Server System CLR Types was not attempted to be installed. [08 / 10 / 11, 14:26:02