Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  Advanced Search
  HOME    TRACKER    MS SQL Server


SuperbHosting.net have generously sponsored dedicated servers to ensure a reliable and scalable dedicated hosting solution for BigResource.com.





Split Function In A Transaction


I have some sql results coming out as a string when it is a bunch of numbers separated with a coma. (1,2,3). I need to insert this figures as separate numbers in separate rows into a table in a database. How do I split them and how do I input them. I tried using a loop and it works well in an asp page but I need to do that in sql.

JG




View Complete Forum Thread with Replies

Related Forum Messages:
Split Function
 

  Is there any split function in sql server 2005.  I just want to pass a string to a stored procedure. it should split that string when it encounters a space. for ex, consider the string    " the intel mother board"  it should give "the,intel,mother,board" as result.

 

 

View Replies !
Split Function
Hi

I have tried like this. but I cant execute my SP it ended up with errors.

IF (@FirstLetters IS NOT NULL)
BEGIN
SET @FirstLetter = 'SELECT SplitValue FROM dbo.FnSplitString('+@FirstLetters+','',''))'
print @FirstLetter
END

SELECT
P.PUB_ID AS ''PubId'',
P.PUB_TITLE AS ''PubTitle''

FROM HDS_PUBLICATION P
INNER JOIN HN_IM_JOIN IM
ON IM.PUB_UNID = P.PUB_UNID,
HDS_CUSTOM C,
WD_PUBLIC_SHELF S,
HDS_TOPIC T
WHERE P.PUB_UNID = C.PUB_UNID AND C.CUSTOM3 = ''False''
AND P.PUB_ID = S.PUB_ID
AND P.PUB_UNID = T.PUB_UNID
AND S.Audience = ''Public''
' + @FilterByLang + '
ANDP.PUB_TITLE LIKE '+ @FirstLetter +'''%''' +'

EXEC SP

Any one please clear me

Thanks,
shakthiA

View Replies !
How To Split A Large Transaction?
I have a huge table with ~30G data, and a column needs to be updated. In order to avoid a huge transaction, what I did was setting up a loop, update part of the records in each loop. The query is like following:



Declare @mo smalldatetime
Declare MOs cursor
for
            Select [a month] from [a table]

Open MOs
Fetch Next from MOs into @mo
while  @@FETCH_STATUS = 0
Begin
            exec sp_UpdateColumn @mo
--          PRINT @mo
            Fetch Next from MOs into @mo
end
close MOs
deallocate MOs
 
sp_UpdateColumn is the query that actually does the update, the code is like following:

Create Procedure sp_UpdateColumn    @updMoDate smalldatetimeAS
[do some calculation here, store results in a temp table #Temp1]
Begin TranUpdate A set col =b.col from  [big table] A,  #Temp1 B where [some matching conditions]Commit GO


The BEGIN TRAN and COMMIT lines were meant to break up transaction, however, our database support people still tell me that a huge transaction has generated a GB sized log file that blocked the drive. Unless the transaction wasn't really splitted this should not happen. Can someone help me take a look at the code and tell me is there anything wrong? Thanks

View Replies !
Split Function With Cursor
Hi,
I am trying to write a stored procedure that takes a comma separated letter. I have a split function that returns the splitted letters. I have select some values from the tables in the database where the title starts with each splitted letter. I thought I should use cursor that contains each letter and in the while loop i put my select statement with the conditions.
Is this the correct way. Or are there any ideas for this?

thanks,

Regards,
shakthi

View Replies !
Split Function - Sql Server 2005
In my table, column1 having a comma separated values.I want to display in rowwise.
for example:
column1
aa,ss,ff
 
output should be
aa
ss
ff
 
Pls. help me..I want to do thr query.

View Replies !
How To Split A Transaction Table To Create Training And Testing Set For AR
Hi all, 

I have a transaction table that has a composite key made up of transaction id and product id. where multiple products were purchased under same transaction, transaction ids got repeated. 

I would like to split the table randomly into 70%, 30% ratio to create training and testing set respectively in such a way that it does not split a same transaction under which multiple products were purchased (rows with same transaction id should not get split).


is it possible? if possible what is the idea?
It would be of great help.


Thanks.


Fakhrul

View Replies !
Can A DTS Function Update The Transaction Log
I have an application which uses DTS to import data. After the data is imported the transaction logs are no good since the import wasn't logging.
Is there a way to turn logging on?

Thanks

View Replies !
Usage Of Count() Function Inside Sql Transaction
Please find my second post in this thread.

Can anyone help me in sorting out the problem and let me know what might be the reason.

Thanks & Regards

Pradeep M V

View Replies !
Insert Stored Procedure With Error Check And Transaction Function
Hi, guys
I try to add some error check and transaction and rollback function on my insert stored procedure but I have an error "Error converting data type varchar to smalldatatime" if i don't use /*error check*/ code, everything went well and insert a row into contract table.
could you correct my code, if you know what is the problem?

thanks

My contract table DDL:
************************************************** ***

create table contract(
contractNum int identity(1,1) primary key,
contractDate smalldatetime not null,
tuition money not null,
studentId char(4) not null foreign key references student (studentId),
contactId int not null foreign key references contact (contactId)
);


My insert stored procedure is:
************************************************** *****

create proc sp_insert_new_contract
( @contractDate[smalldatetime],
@tuition [money],
@studentId[char](4),
@contactId[int])
as

if not exists (select studentid
from student
where studentid = @studentId)
begin
print 'studentid is not a valid id'
return -1
end

if not exists (select contactId
from contact
where contactId = @contactId)
begin
print 'contactid is not a valid id'
return -1
end
begin transaction

insert into contract
([contractDate],
[tuition],
[studentId],
[contactId])
values
(@contractDate,
@tuition,
@studentId,
@contactId)

/*Error Check */
if @@error !=0 or @@rowcount !=1
begin
rollback transaction
print ‘Insert is failed’
return -1
end
print ’New contract has been added’

commit transaction
return 0
go

View Replies !
Error 8525: Distributed Transaction Completed. Either Enlist This Session In A New Transaction Or The NULL Transaction.
Hi All
 
I'm getting this when executing the code below.  Going from W2K/SQL2k SP4 to XP/SQL2k SP4 over a dial-up link.
 
If I take away the begin tran and commit it works, but of course, if one statement fails I want a rollback.  I'm executing this from a Delphi app, but I get the same from Qry Analyser.
 
I've tried both with and without the Set XACT . . ., and also tried with Set Implicit_Transactions off.
 
set XACT_ABORT ON
Begin distributed Tran
update OPENDATASOURCE('SQLOLEDB','Data Source=10.10.10.171;User ID=*****;Password=****').TRANSFERSTN.TSADMIN.TRANSACTIONMAIN
 set REPFLAG = 0 where REPFLAG = 1
update TSADMIN.TRANSACTIONMAIN
 set REPFLAG = 0 where REPFLAG = 1 and DONE = 1
update OPENDATASOURCE('SQLOLEDB','Data Source=10.10.10.171;User ID=*****;Password=****').TRANSFERSTN.TSADMIN.WBENTRY
 set REPFLAG = 0 where REPFLAG = 1
update TSADMIN.WBENTRY
 set REPFLAG = 0 where REPFLAG = 1
update OPENDATASOURCE('SQLOLEDB','Data Source=10.10.10.171;User ID=*****;Password=****').TRANSFERSTN.TSADMIN.FIXED
 set REPFLAG = 0 where REPFLAG = 1
update TSADMIN.FIXED
 set REPFLAG = 0 where REPFLAG = 1
update OPENDATASOURCE('SQLOLEDB','Data Source=10.10.10.171;User ID=*****;Password=****').TRANSFERSTN.TSADMIN.ALTCHARGE
 set REPFLAG = 0 where REPFLAG = 1
update TSADMIN.ALTCHARGE
 set REPFLAG = 0 where REPFLAG = 1
update OPENDATASOURCE('SQLOLEDB','Data Source=10.10.10.171;User ID=*****;Password=****').TRANSFERSTN.TSADMIN.TSAUDIT
 set REPFLAG = 0 where REPFLAG = 1
update TSADMIN.TSAUDIT
 set REPFLAG = 0 where REPFLAG = 1
COMMIT TRAN

 
It's got me stumped, so any ideas gratefully received.Thx

View Replies !
SSIS, Distributed Transaction Completed. Either Enlist This Session In A New Transaction Or The NULL Transaction.
I have a design a SSIS Package for ETL Process. In my package i have to read the data from the tables and then insert into the another table of same structure.

for reading the data i have write the Dynamic TSQL based on some condition and based on that it is using 25 different function to populate the data into different 25 column. Tsql returning correct data and is working fine in Enterprise manager. But in my SSIS package it show me time out ERROR.

I have increase and decrease the time to catch the error but it is still there i have tried to set 0 for commandout Properties.

if i'm using the 0 for commandtime out then i'm getting the Distributed transaction completed. Either enlist this session in a new transaction or the NULL transaction.

and

Failed to open a fastload rowset for "[dbo].[P@@#$%$%%%]". Check that the object exists in the database.

Please help me it's very urgent.

View Replies !
Distributed Transaction Completed. Either Enlist This Session In A New Transaction Or The NULL Transaction.
Hi all, I've already read the thread by the same topic, but I found Kevin Yu's comment a bit confusing.  I don't know how to solve my problem.  I have two stored procedures in sql server.  First one inserts into a bunch of tables so it has Begin Transaction and Commit in it.  Second one just inserts into one table so it doesn't have the begin transaction statement in it. From my data access class in c#.net, I have a function which calls both of these stored procedures from within a "using transactionscope" block.  So when it makes the call to the first stored procedure, it returns fine, but when it calls the second one, I get the above error.   I think it has something to do with me declaring transactionscope in my application code, and then calling a stored procedure which also has its own begin transaction.  But I don't know how to fix this.  Any ideas? Thanks 

View Replies !
Distributed Transaction Completed. Either Enlist This Session In A New Transaction Or The NULL Transaction
I'm using TransactionScope object and it is giving me problems. The situation is like this.
I've 2 tables in sql server express, say student and courses and other one studentcourse for courses a student has opted for.
An aspx page displays list of users in listbox, when user chooses student, it fetches courses he has opted for and in the checkedlistbox (for courses) these courses are checked. Now when uses makes any changes to courses and clicks update button, i've
two functions at backend first one removes the courses which were previously selected but now not selected in postback, next it inserts courses which was not selected first but now are in this postback.
I use following code:

protected void Update(object sender, EventArgs e)
{
/*
get selections, existing courses etc.
*/
using(TransactionScope tscope=new TransactionScope())
{
try
{
RemoveCourses(/*Student*/ s, /*IList*/ oldCourses, /*IList*/ newCourses);
AddCourses(/*Student*/ s, /*IList*/ oldCourses, /*IList*/ newCourses);
tscope.Complete();
}
catch(Exception ex)
{
lblMessage.Text=ex.Message;
}
}
}

If any exception occurs during update and page is reload or I go to any other page where some data is fetched from sql server I get the exception:
Distributed transaction completed. Either enlist this session in a new transaction or the NULL transaction

Please help!

View Replies !
Distributed Transaction Completed. Either Enlist This Session In A New Transaction Or The NULL Transaction.
I am getting this error  :Distributed transaction completed. Either enlist this session in a new
transaction or the NULL transaction. Description:
An unhandled exception occurred during the execution of the current web
request. Please review the stack trace for more information about the error and
where it originated in the code. Exception Details:
System.Data.OleDb.OleDbException: Distributed transaction completed. Either
enlist this session in a new transaction or the NULL transaction.have anybody idea?!

View Replies !
Distributed Transaction Completed. Either Enlist This Session In A New Transaction Or The NULL Transaction.
i have a sequence container in my my sequence container i have a script task for drop the existing tables. This seq. container connected to another seq. container. all these are in for each loop container when i run the package it's work fine for 1st looop but it gives me error for second execution.

Message is like this:

Distributed transaction completed. Either enlist this session in a new transaction or the NULL transaction.

View Replies !
Distributed Transaction Completed. Either Enlist This Session In A New Transaction Or The NULL Transaction. (HELP)
Hi,
 
i am getting this error "Distributed transaction completed. Either enlist this session in a new transaction or the NULL transaction.".
 
my transations have been done using LINKED SERVER. when i manually call the store procedure from Server 1 it works but when i call it through Service broker it dosen't work and gives me this error.
 
 
 
Thanks in advance.
 
 
 

View Replies !
TRANSACTIONS In SSIS (error: The ROLLBACK TRANSACTION Request Has No Corresponding BEGIN TRANSACTION.&&"
I'm receiving the below error when trying to implement Execute SQL Task.

"The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION." This error also happens on COMMIT as well and there is a preceding Execute SQL Task with BEGIN TRANSACTION tranname WITH MARK 'tran'

I know I can change the transaction option property from "supported" to "required" however I want to mark the transaction. I was copying the way Import/Export Wizard does it however I'm unable to figure out why it works and why mine doesn't work.

Anyone know of the reason?

View Replies !
Unable To Shrink Transaction Log Under Transaction Replication With Sync With Backup Enabled On Distribution Db?
We have applied transaction replication servers with SQLServer2005 standard edition with SP1 running on them. Sync with backup is also enabled on distribution db. Now our transaction log is not shrinking using standard shrinking procedure(taking log backup with truncate option/shrinkfile).

select name,log_reuse_wait, log_reuse_wait_desc from sys.databases

it is showing  dbname, 6, Replication respectively.
 

declare @db int

 

set @db=db_id('dbname')

dbcc loginfo(@db)
 

is showing 2 in status column.
tried shrinking transaction file after removing sync with backup option from distribution db. still it failed. again tried shrinking after stopping log reader, it didn't worked.
 
Regards,
M. Abdullah Idris

View Replies !
I Need Away To Show The Pending Transaction From Transaction Replication In A User Friendly Format.
 

I want to list out the pending transaction for transaction replication  by publication.

 

Help needed.

View Replies !
Retrieving Result Set From Dynamically Called Stored Procedure Or Function In A Function
Is there any way I can retrieve the result set of a Stored Procedurein a function.ALTER FUNCTION dbo.fn_GroupDeviceLink(@groupID numeric)RETURNS @groupDeviceLink TABLE (GroupID numeric, DeviceID numeric)ASBEGINDeclare @command nvarchar(255)SELECT @command = Condition// @command is an SQL string or stored procedue nameFROM DeviceGroupWHERE GroupID = @groupIDINSERT @groupDeviceLinkEXEC @commandRETURNENDIs there any way i can do anything like this. @command is a variableholding the name of a stored produre. I need to run that storedprocure and return the values in such a way that they can be used in aSELECT StatementMy goal is SELECT * FROM Device INNER JOINdbo.fn_GroupDeviceLink(@groupID) ON ....this fn_GroupDeviceLink should run the proper stored procedure andreturn the values. What i also want to do is play with that result setof the specific stored procedure before i return it. Is this possible?If not, what is the work arround?ThanksMark

View Replies !
Using Begin Transaction,End Transaction, Return,Rollback, Break,Continue
Hi, is there someone who can demonstrate the usgae of these codes in this simple process. I have a table that has (id int, Balance money)
I want to write codes to utilize the Subject coding in this process.
1.Every time I withdraw money from a client, I want to verrify that he/she has enough money if not I want to roll back transaction.
2.Using Begin Tran , end Tran..
3. Using Return ,Break,continue

I really appreciate your help. Althought I read about this from a book, but it really confused me and I want to see real world example using client and withdraw from there accounts...:)

regards
Ali

View Replies !
How Do I Make Use Of Begin Transaction And Commit Transaction In SSIS.
Hi

 

How do I make use of begin transaction and commit transaction in SSIS.

As am not able to commit changes due to certain update commands I want to explicitly write begin and commit statements. but when i make use of begin and commit in OLEDB commnad stage it throws an error as follows:

Hresult:0x80004005

descriptionyntax error or access violation.

 

its definately not an syntax error as i executed it in sql server. also when i use it in execute sql task out side the dataflow container it doesnt throw any error but still this task doesnt serve my purpose of saving/ commiting update chanages in the database.

 

Thanks,

Prashant

View Replies !
Help Convert MS Access Function To MS SQL User Defined Function
I have this function in access I need to be able to use in ms sql.  Having problems trying to get it to work.  The function gets rid of the leading zeros if the field being past dosn't have any non number characters.For example:TrimZero("000000001023") > "1023"TrimZero("E1025") > "E1025"TrimZero("000000021021") > "21021"TrimZero("R5545") > "R5545"Here is the function that works in access:Public Function TrimZero(strField As Variant) As String   Dim strReturn As String   If IsNull(strField) = True Then      strReturn = ""   Else      strReturn = strField      Do While Left(strReturn, 1) = "0"         strReturn = Mid(strReturn, 2)      Loop   End If  TrimZero = strReturnEnd Function

View Replies !
In-Line Table-Valued Function: How To Get The Result Out From The Function?
Hi all,
 
I executed the following sql script successfuuly:
 
shcInLineTableFN.sql:

USE pubs

GO

CREATE FUNCTION dbo.AuthorsForState(@cState char(2))

RETURNS TABLE

AS

RETURN (SELECT * FROM Authors WHERE state = @cState)

GO
 
And the "dbo.AuthorsForState" is in the Table-valued Functions, Programmabilty, pubs Database.
 
I tried to get the result out of the "dbo.AuthorsForState" by executing the following sql script:
 
shcInlineTableFNresult.sql:

USE pubs

GO

SELECT * FROM shcInLineTableFN

GO

 
I got the following error message:

Msg 208, Level 16, State 1, Line 1

Invalid object name 'shcInLineTableFN'.

 
Please help and advise me how to fix the syntax

"SELECT * FROM shcInLineTableFN"
and get the right table shown in the output.
 
Thanks in advance,
Scott Chang

View Replies !
Usage Of Begin Transaction.... Commit Transaction??
Hi, anyone can help,I am trying to learn how to use begin tran..commit tran .. rollback tran by doing this exercise... unfortunatelly,it did not work...anyone can help...
I have a table named tbl_balance(investor_id int,amount money)
I want to insert/update balance for each investor. I wrote a procedure but it didnot work:::

declare @investorid int, @amount money,@error_status int
select @investorid=1
select @amount = 500
/* to check if investor exist in the tbl_balance table, if so execute the codes */
IF exists(select investorid from tbl_bal where investorid=@investorid )
begin tran
begin
update tbl_balance
set amount=amount+@amount
where investorid =@investorid

if (@error_status<> 0)
begin
ROLLBACK tran
select 'you did not update'
end
else
begin
COMMIT tran
select ' YOu did update '
end
end

IF not exists(select investorid from tbl_bal where investorid=@investorid )
begin tran
begin
insert into tbl_balance
values(@investorid,@amount)

if (@error_status<> 0)
begin
ROLLBACK tran
select 'you did not update'
end
else
begin
COMMIT tran
select ' YOu did update '
end
end

View Replies !
Problem With SSIS Transaction...Transaction Scope
 

Hi,

I am having some problem with SSIS transaction. Eventhought I tried to imitate the concept that Jamie presented at http://www.sqlservercentral.com/columnists/jthomson/transactionsinsqlserver2005integrationservices.asp

. My workflow is as followed

*********************************
For Each ADO.Record in Oracle (transaction=not supported)

If (Certain_Field_Value = 'A')


Lookup Data in SQL DB with values from Oracle (transaction=not supported)

DO Sequence A (Start a Transaction , transaction=required)


INSERT/UPDATE some records in SQLDB(transaction=supported)
Finish Sequence A ( transaction should stop here)
UPDATE Oracle DB ( Execute SQLTask, transaction=not supported)
If (Certain_Field_Value = 'B')


Lookup Data in SQL DB with values from Oracle (transaction=not supported)

DO Sequence B (Start a Transaction , transaction = required)


INSERT/UPDATE some records in SQLDB (transaction=supported)
Finish Sequence A ( transaction should stop here)
UPDATE Oracle DB ( Execute SQLTask, transaction=not supported)
If (Certain_Field_Value = 'C')

------------
------------
End ForEach Loop
*************************************
My requirements are that I want separate transaction for each Sequence A, B, C, etc... If Sequence A transaction fails, the other should still be continuing with another transaction.
But I am getting an error regarding the OLEDB Error in next Task (e.g in Certain_Field_Value = 'B') "Lookup Data in SQL DB with values from Oracle ", the error message is  ".......Distributed transaction completed. Either enlist this session in a new transaction or the NULL transaction. ".
What is it that I am doing wrong?
Regards
KyawAM

View Replies !
Sql2005:Cannot Use SAVE TRANSACTION Within A Distributed Transaction
Error returned when trying to commit the transaction to a database that is a replication distributor. (sql2005 ctp16)

View Replies !
Name Split
Quick question.

I've got a CHAR (70) field called NAME that has a first and last name separated by a space. I want to split it into two fields FIRST and LAST -- with all the characters to the left of the space a first name and all the characters to the right of the space as last name. I couldn't find a string function that would let me do this simply (it may be right in front of me and I missed it).

Thanks in advance.

Ray

View Replies !
Name Split
I need to split a column of Full Names into First name and Last name columns. Has someone come across this before and if so can you give me an idea of how to overcome it?

View Replies !
Split Value In Sql
Hi to all

I have one problem regarding sp and pass value in sp
I am gating a value like Abc,Def,Ghi,

Now I want to split the whole pass value by “,�
And fire one for loop to store value in database
This things is done in asp.net web form but I want to do all process in sp
So please guide me how I am write sp .
The purpose is pass value one time so connection time is decrees and give fast perforce

View Replies !
To Split Or Not To Split
I have a database with a "large" table containing date based information Basically they're reservations. I've thought about creating a new table and adding any records from past years to this table. For the most part only current reservation need to be searchable, but in some circumstances it would be useful to be able to search through the archive too. so, my questions!!!

Is 8,000 or so rows of data "large" and unwieldly in SQL terms?

Would splitting this data into 2 tables - one small table for current and future reservations and one larger archive table then using a UNION SELECT query to make archive information seachable be a significant improvment on server resources/load or am I making the whole thing more complicated than it need be as 8,000 rows of data is nothing to worry about.............

What did they say about a little bit of knowledge being a dangerous thing?

Thanks in advance of any guidance to a neophyte!!?

View Replies !
SPLIT() UDF
SQL UDF split()

The objective of this article is to help the SQL developers with an UDF that can be used within a stored procedures or Function to split a string (based on given delimiter) and extract the required portion of the string.

Scripting languages like VB script and Java script have in-built split() functions but there is no such function available in SQL server. In my experience this function is really handy when you’re working on an ASP application with SQL server as backend, whereby you’ll need to pass the ASP page submitted values to the SQL stored procedure.

To give a simple example, in a typical Monthly reporting ASP page – the users would select a range of months and extract the information pertaining to this date range. Classic implementation of this model is to have an ASP page to accept the input parameters and pass the values to the SQL stored procedure (SP). The SP would return a result set which is then formatted in the ASP page as results.

If the date range is continuous ie. JAN07 to MAR07 then the SP can typically accept a ‘From’ and ‘To’ range variables. But I’ve encountered situations whereby the users select 3 months from the current year and 2 months from previous year (non-continuous date ranges). In such scenario the SP cannot have a date range as input parameters.

Typically an ASP programmer would do is by having a single date input parameter in the SP and call the SP within a loop in the ASP page. This is an inefficient way of programming as contacting the database server within an ASP loop could cause performance overhead especially if the table being queried is an online transaction processing table.

Here is how I handled the above situation.

1.Declared one string input parameter of type varchar(8000) (if you’re using SQL 2005 then it is advisable to use Varchar(Max))
2.Pass the ASP submitted values as string, in this case the months selected by user would be supplied to the SP as a string
3.Within the Stored Procedure I’ll call the split() function to extract each month from the string and query the corresponding data

The basic structure of the stored procedure is as pasted below:-

CREATE PROCEDURE FETCH_SALES_DETAIL (
@MONTH VARCHAR(MAX)
)
AS
BEGIN
DECLARE @MONTH_CNT INT,@MTH DATETIME
SET @MONTH_CNT=1
WHILE DBO.SPLIT(@MONTH,',',@MONTH_CNT) <> ''
BEGIN
SET @MTH = CAST(DBO.SPLIT(@MONTH,',',@MONTH_CNT) AS DATETIME)
--<<Application specific T-SQLs>>-- (BEGIN)
SELECT [SALES_MONTH],[SALES_QTY],[PRODUCT_ID],[TRANSACTION_DATE]
FROM SALES (NLOCK)
WHERE [SALES_MONTH]= @MTH
--<<Application specific T-SQLs>>--(END)

SET @MONTH_CNT=@MONTH_CNT+1
END
END

Dbo.SPLIT() function takes 3 parameters
1)The main string with the values to be split
2)The delimiter
3)The Nth occurrence of the string to be returned

The functionality of the UDF is as explained STEP by STEP:

1.Function Declaration
CREATE FUNCTION [dbo].[SPLIT]
(
@nstring VARCHAR(MAX),
@deliminator nvarchar(10),
@index int
)

RETURNS VARCHAR(MAX)

Function is declared with 3 input parameters:-
@nstring of type VARCHAR(MAX) will hold the main string to be split
@deliminator of type NVARCHAR(10) will hold the delimiter
@index of type INT will hold the index of the string to be returned
2.Variable Declaration
DECLARE @position int
DECLARE @ustr VARCHAR(MAX)
DECLARE @pcnt int

Three variables are needed within the function. @position is an integer variable that will be used to traverse along the main string. @ustr will store the string to be returned and the @pcnt integer variable to check the index of the delimiter.
3.Variable initialization
SET @position = 1
SET @pcnt = 1
SELECT @ustr = ''
Initialize the variables
4.Main functionality
WHILE @position <= DATALENGTH(@nstring) and @pcnt <= @index
BEGIN
IF SUBSTRING(@nstring, @position, 1) <> @deliminator BEGIN
IF @pcnt = @index BEGIN
SET @ustr = @ustr + CAST(SUBSTRING(@nstring, @position, 1) AS nvarchar)
END
SET @position = @position + 1
END
ELSE BEGIN
SET @position = @position + 1
SET @pcnt = @pcnt + 1
END
END

4.1The main while loop is used to traverse through the main string until the word index is less than or equal to the index passed as input parameter.
4.2Within the while loop each character within the string is verified against the delimiter and if it does not match then local word count variable is checked against the input index parameter
4.3If the values are same ie., the input variable index and the word being processed in the while loop are the same then the word is stored in the @ustr variable. If the values does not match then the @position variable is incremented.
4.4If the character matches with the delimiter then the word count variable @pcnt is incremented along with the @position variable

5.Return the value
RETURN @ustr

I hope this article would benefit those who are looking for a handy function to deal with Strings.

Feel free to send your feedback at dearhari@gmail.com

View Replies !
A Function Smilar To DECODE Function In Oracle
I need to know how can i incoporate the functionality of DECODE function like the one in ORACLE in mSSQL..
please if anyone can help me out...


ali

View Replies !
Using RAND Function In User Defined Function?
Got some errors on this one...

Is Rand function cannot be used in the User Defined function?
Thanks.

View Replies !
I Want A Function Like IfNull Function To Use In Expression Builder
Hi,

I wonder if there a function that i can use in the expression builder that return a value (e.g o)  if the input value is null ( Like ifnull(colum1,0)  )

 

i hope to have the answer because i need it so much.

 

Maylo

View Replies !
How To Split A String Using Sql
I have 5 dynamic rows each row consisting of 5 checkboxes & 5 dropdowns.I am concatenating the values of each controls in a row using a wildcard charater "~" and each row i am concatenating using "|".The complete string is then assigned to one hidden field and passed as sql parameter to the backend.

Please help in writing the split function to get the values of each checkboxes and dropdowns from the string in order to save them in separate columns.

Thanks

View Replies !
SQL Search Split
CREATE PROCEDURE [dbo].[ShowComboLocation]@Keyword varchar(50) ASSELECT TOP 100 PERCENT PropertyAreaID, PropertyAreaFROM dbo.iViewAllWHERE (PropertyArea LIKE '%' + @Keyword + '%')GOQuestion 1 isIf Keyword ="London WestEnd Harrods", I know my query will end up like this (PropertyArea LIKE 'London WestEnd Harrods')But I want to to individually search for 3 or 1-nth words therefore my query should end up like this(PropertyArea LIKE 'London')OR (PropertyArea LIKE 'WestEnd')OR (PropertyArea LIKE 'Harrods')i WANT TO perform this on my SQL STored Procedure,Can anybody provide code or links pls

View Replies !
Reg Split Funtion
Hi,

Is it possible to split the following value in sql server ?

I have the value like 25 Email Accounts,50 Email Accounts in my sqlserver database.
Here i need only the numeric value .ie 25,50.Is it possible? can any one give me the solution ..

I am using ASP.Net and C# backend is SQL Server 2000.

Thanks and Regards
Arul

View Replies !
Split A Field
Whats the best way to do the following?Field1 in Table1 contains numbers and characters seperated by #Examples: aaa#01, kjhkjhjh#21 and jlkjlkj#123How can I create two new fields in Table1, one containing what is tothe left of the # and the other what is to the right?Regards,Ciarán

View Replies !
Split A Column
Hi everybody

Does any body know how to split a field in a table into two fields

eg
usermaster(table)
userid(field)

usermaster has 40 users with user id 1 to 40
i want to get data as

userid userid
1 21
2 22
3 23
. .
. .
. .
20 40

Thanks you very much

View Replies !
Split Tables And Keep ID
I have a large table that I'm planning on splitting out into 5 smaller ones. What I need to do is maintain some central repository for auto-numbering new records to make sure that no 2 records in different tables have the same unique ID. Thanks in advance!

View Replies !
Split A String
Hi
I have this string which might have a hyphen in it "-"
What I want to do is
if I get a hyphen then take all characters after hyphen
else take only all the characters starting from the 5th position of the string
How can this be achieved?

View Replies !
Split A String In Sql
Hi I need a stored procedure in SQL that will split a comma separated variable passed to it
select a name for each value and return a recordset. Any pointers greatfully received.
First attempt is dreadfully slow as I am opening recordsets each time

Function func_getFood()
Dim rsfoodsql
Dim foodoutput
for x=1 to ubound(masterfoodarray)-2
set rsfoodsql= objconn.execute ("select foodname from tbl"&language&"food where foodID='"& masterfoodarray(x) &"'")
if not rsfoodsql.eof then
foodoutput=rsfoodsql("foodname")
if not foodoutput="" then
response.write foodoutput&"<BR>"
end if
end if
next
End Function

Hope someone can help,
cheers

View Replies !
Should I Split The Procedure Or Not???
I have a procedure that is going to be called through asp pages. This procedure carries out instructions depending on whether customers wants to insert, update or delete their portfolios. Rules are as follows: 1. It should not allow duplicate portfolio name to insert. 2. If customer has reached their max limit of 20 portfolio they can't add. They may have to delete or update the existing portfolio first. 3. all the error handling is done and returned as output parameters.

Now coming to the question at present I have one procedure that does all these things. Should I split up the procedure and have three procedures handling the events seperately: 1 Insert 2 Delete 3 update The reason I am concerned is 1 procedure being hit so many times by concurrent users with varying events. I am concerned about performance issue and slowing down of the page. I do not have exact numbers of users at this point. But they would be in thousands or more. Thanks for any suggestions or advice you all might have to share. Hiku

View Replies !
Split A Fullname
I want to know how to parse a fullname into a fname and lname.

View Replies !
Split Relationship ?
What I have is a table with a primary key. Then I have 5 other tables with a relating key. No problems there.

I need to create a relationship with the primary table (primary) key who's data field is 25 charachters. I need to parse that out and have 3 charachters go to one, 2 to the other and so on.

I don't know how to do that, can you help?

View Replies !
Split Pipeline
 

This is probably obvious, but how do I split a pipeline. I.e. I've got a data source with 200 columns - I need to split this into 20 pipelines each containing 10 of the original columns.

View Replies !
Split The File
my ssis package downloades the text file from Ftp. iT downloades for ex 5 files.

I want to split the file to smaller file after downloades. If the size of file is more then 600 mB then I want to split it into 6 files.

please suggest if any task in SSIS can perform this or any other way.

 

View Replies !
Tell To Split On Change Of ID
how can I tell the conditional component to split the records based on change of hdr_HeaderID

http://www.webfound.net/split_on_headerid.jpg

let me know if you need more info...

 

View Replies !
Conditional Split
 

Hi,
  In my Excel file I have the columns Col1, Col2. I want to send those records to Sqlserver table only if the Col1 and Col2 is not null.
For this I am using the Conditional Split expression like this: (!ISNULL([Col1])) && (!ISNULL([Col2])). And sending this result to Sqlserver table. But I am not getting any records into the table. But the records col1 and col2 not null exist in Excel file. Is there any thing wrong in my expression?
 
Thanks in advance
 

View Replies !

Copyright © 2005-08 www.BigResource.com, All rights reserved