March 17, 2012 at 3:23 am
It seems like this is not for production server. Not sure though.
Sivaganesh soon you will learn cursors are not the best friend for sql solution.
--- babu
March 17, 2012 at 8:47 am
Kingston Dhasian (3/17/2012)
Jeff Moden (3/16/2012)
er.sivaganesh (3/16/2012)
thanks for every one who joined in this discussion i just solved this problem by creating cusor in my store procedureGosh... after all the warnings about cursors and you still used one. I hope, for your employer's or customer's sake, it's truly something that requires a cursor instead of what you said you were going to use it for.
This link below will give you an idea of why he wanted a CURSOR
http://www.sqlservercentral.com/Forums/Topic1267085-391-1.aspx
Ah... I see. From the other thread you posted.
but i need to search more word as like google search
Since there's a bit more clarity as to what the problem is on that other post, I'm going over there and see if I can dig out what is actually needed. If I'm guessing correctly, I may know what he needs if I can just get him over the idea of using a cursor for this.
Thanks, Kingston.
--Jeff Moden
Change is inevitable... Change for the better is not.
March 17, 2012 at 12:31 pm
alter PROCEDURE [dbo].[SP_Searchengine]
@VALUES varchar(8000)
AS
BEGIN
create table solution
(
AdSpaceId int,
AdInfoId int,
BusinessName varchar(200),
AdSpaceName varchar(200),
FileName varchar(200),
TotalBlocks int
)
declare @table table
(
items varchar(8000)
)
Insert into @table( items)
select items from [characterSplit](@VALUES,'')
DECLARE @AccountID varchar(200)
DECLARE @getAccountID CURSOR
SET @getAccountID = CURSOR FOR
SELECT
items
FROM
@table
OPEN
@getAccountID
FETCH NEXT
FROM
@getAccountID INTO @AccountID
WHILE @@FETCH_STATUS = 0
BEGIN
SET @AccountID = REPLACE(RTRIM(LTRIM(@AccountID)), ' ', '%' );
insert into solution( AdSpaceId,AdInfoId,BusinessName,AdSpaceName,FileName,TotalBlocks)
select
s.AdSpaceId
,i.AdInfoId
,i.BusinessName
,s.AdSpaceName
,s.FileName
,s.TotalBlocks
from
tblAdSpace s
join
tblMembers m on m.MemberId=s.MemberId
join
tblAdInfo i on s.AdSpaceId=i.AdSpaceId
join
tblAdBlock b on s.AdSpaceId=b.AdSpaceId
join
tblAdContactInfo INF ON INF.AdInfoId=i .AdInfoId
join
tblApplicableCategories ACS ON ACS.AdInfoId= i .AdInfoId
join
tblAdCategory ac ON ac.CategoryId =ACS.AdInfoId
join
tblAdSubCategory sb ON sb .CategoryId = ACS.AdInfoId
WHERE
s.AdSpaceName LIKE '%'+ @AccountID + '%'
or
s.FileName LIKE '%'+ @AccountID + '%'
or
m.Mobile LIKE '%'+ @AccountID + '%'
or
m.FirstName LIKE '%'+ @AccountID + '%'
or
m.LastName LIKE '%'+ @AccountID + '%'
or
m.LastName LIKE '%'+ @AccountID + '%'
or
i.BusinessName LIKE '%'+ @AccountID + '%'
or
i.Notes LIKE '%'+ @AccountID + '%'
or
INF.Value LIKE '%'+ @AccountID + '%'
or
ac .CategoryName LIKE '%'+ @AccountID + '%'
or
sb.SubCategoryName LIKE '%'+ @AccountID + '%'
FETCH NEXT
FROM
@getAccountID INTO @AccountID
END
CLOSE
@getAccountID
DEALLOCATE
@getAccountID
select AdSpaceId,AdInfoId,BusinessName,AdSpaceName,FileName,TotalBlocks from solution
drop table solution
END
for this only i just cursor i used cursor if there is any other way just tell me
here i used split function for spliting input words
March 17, 2012 at 1:04 pm
er.sivaganesh (3/17/2012)
alter PROCEDURE [dbo].[SP_Searchengine]
@VALUES varchar(8000)
AS
BEGIN
create table solution
(
AdSpaceId int,
AdInfoId int,
BusinessName varchar(200),
AdSpaceName varchar(200),
FileName varchar(200),
TotalBlocks int
)
declare @table table
(
items varchar(8000)
)
Insert into @table( items)
select items from [characterSplit](@VALUES,'')
DECLARE @AccountID varchar(200)
DECLARE @getAccountID CURSOR
SET @getAccountID = CURSOR FOR
SELECT
items
FROM
@table
OPEN
@getAccountID
FETCH NEXT
FROM
@getAccountID INTO @AccountID
WHILE @@FETCH_STATUS = 0
BEGIN
SET @AccountID = REPLACE(RTRIM(LTRIM(@AccountID)), ' ', '%' );
insert into solution( AdSpaceId,AdInfoId,BusinessName,AdSpaceName,FileName,TotalBlocks)
select
s.AdSpaceId
,i.AdInfoId
,i.BusinessName
,s.AdSpaceName
,s.FileName
,s.TotalBlocks
from
tblAdSpace s
join
tblMembers m on m.MemberId=s.MemberId
join
tblAdInfo i on s.AdSpaceId=i.AdSpaceId
join
tblAdBlock b on s.AdSpaceId=b.AdSpaceId
join
tblAdContactInfo INF ON INF.AdInfoId=i .AdInfoId
join
tblApplicableCategories ACS ON ACS.AdInfoId= i .AdInfoId
join
tblAdCategory ac ON ac.CategoryId =ACS.AdInfoId
join
tblAdSubCategory sb ON sb .CategoryId = ACS.AdInfoId
WHERE
s.AdSpaceName LIKE '%'+ @AccountID + '%'
or
s.FileName LIKE '%'+ @AccountID + '%'
or
m.Mobile LIKE '%'+ @AccountID + '%'
or
m.FirstName LIKE '%'+ @AccountID + '%'
or
m.LastName LIKE '%'+ @AccountID + '%'
or
m.LastName LIKE '%'+ @AccountID + '%'
or
i.BusinessName LIKE '%'+ @AccountID + '%'
or
i.Notes LIKE '%'+ @AccountID + '%'
or
INF.Value LIKE '%'+ @AccountID + '%'
or
ac .CategoryName LIKE '%'+ @AccountID + '%'
or
sb.SubCategoryName LIKE '%'+ @AccountID + '%'
FETCH NEXT
FROM
@getAccountID INTO @AccountID
END
CLOSE
@getAccountID
DEALLOCATE
@getAccountID
select AdSpaceId,AdInfoId,BusinessName,AdSpaceName,FileName,TotalBlocks from solution
drop table solution
END
for this only i just cursor i used cursor if there is any other way just tell me
here i used split function for spliting input words
I believe I can definitely help out here especially in the area of performance. I also need to see your "characterSplit" function because that can be a part of the problem, as well. Thanks.
--Jeff Moden
Change is inevitable... Change for the better is not.
March 17, 2012 at 9:54 pm
CREATE FUNCTION [dbo].[Split](@String varchar(8000), @Delimiter char(1))
returns @temptable TABLE (items varchar(8000))
as
begin
declare @idx int
declare @slice varchar(8000)
select @idx = 1
if len(@String)<1 or @String is null return
while @idx!= 0
begin
set @idx = charindex(@Delimiter,@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String
if(len(@slice)>0)
insert into @temptable(Items) values(@slice)
set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
return
end
this is the character split function which i used
March 18, 2012 at 4:13 am
Here is the procedure, untested, as you did not provide the other items requested (ddl for the tables, sample data).
alter PROCEDURE [dbo].[SP_Searchengine]
@VALUES varchar(8000)
AS
BEGIN
select
s.AdSpaceId
,i.AdInfoId
,i.BusinessName
,s.AdSpaceName
,s.FileName
,s.TotalBlocks
from
tblAdSpace s
join tblMembers m
on m.MemberId=s.MemberId
join tblAdInfo i
on s.AdSpaceId=i.AdSpaceId
join tblAdBlock b
on s.AdSpaceId=b.AdSpaceId
join tblAdContactInfo INF
ON INF.AdInfoId=i .AdInfoId
join tblApplicableCategories ACS
ON ACS.AdInfoId= i .AdInfoId
join tblAdCategory ac
ON ac.CategoryId =ACS.AdInfoId
join tblAdSubCategory sb
ON sb .CategoryId = ACS.AdInfoId
cross apply dbo.DelimitedSplit8K (@values, ',') ds --Replace ',' with your actual delimter
WHERE
s.AdSpaceName LIKE '%'+ replace(ds.Item, ' ', '%') + '%'
or s.FileName LIKE '%'+ replace(ds.Item, ' ', '%') + '%'
or m.Mobile LIKE '%'+ replace(ds.Item, ' ', '%') + '%'
or m.FirstName LIKE '%'+ replace(ds.Item, ' ', '%') + '%'
or m.LastName LIKE '%'+ replace(ds.Item, ' ', '%') + '%'
or m.LastName LIKE '%'+ replace(ds.Item, ' ', '%') + '%'
or i.BusinessName LIKE '%'+ replace(ds.Item, ' ', '%') + '%'
or i.Notes LIKE '%'+ replace(ds.Item, ' ', '%') + '%'
or INF.Value LIKE '%'+ replace(ds.Item, ' ', '%') + '%'
or ac .CategoryName LIKE '%'+ replace(ds.Item, ' ', '%') + '%'
or sb.SubCategoryName LIKE '%'+ replace(ds.Item, ' ', '%') + '%'
END
And here is the code for the function dbo.DelimtedSplit8k:
/****** Object: UserDefinedFunction [dbo].[DelimitedSplit8K] Script Date: 03/18/2012 04:11:23 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[DelimitedSplit8K]
/**********************************************************************************************************************
Purpose:
Split a given string at a given delimiter and return a list of the split elements (items).
Notes:
1. Leading a trailing delimiters are treated as if an empty string element were present.
2. Consecutive delimiters are treated as if an empty string element were present between them.
3. Except when spaces are used as a delimiter, all spaces present in each element are preserved.
Returns:
iTVF containing the following:
ItemNumber = Element position of Item as a BIGINT (not converted to INT to eliminate a CAST)
Item = Element value as a VARCHAR(8000)
Statistics on this function may be found at the following URL:
http://www.sqlservercentral.com/Forums/Topic1101315-203-4.aspx
CROSS APPLY Usage Examples and Tests:
--=====================================================================================================================
-- TEST 1:
-- This tests for various possible conditions in a string using a comma as the delimiter. The expected results are
-- laid out in the comments
--=====================================================================================================================
--===== Conditionally drop the test tables to make reruns easier for testing.
-- (this is NOT a part of the solution)
IF OBJECT_ID('tempdb..#JBMTest') IS NOT NULL DROP TABLE #JBMTest
;
--===== Create and populate a test table on the fly (this is NOT a part of the solution).
-- In the following comments, "b" is a blank and "E" is an element in the left to right order.
-- Double Quotes are used to encapsulate the output of "Item" so that you can see that all blanks
-- are preserved no matter where they may appear.
SELECT *
INTO #JBMTest
FROM ( --# & type of Return Row(s)
SELECT 0, NULL UNION ALL --1 NULL
SELECT 1, SPACE(0) UNION ALL --1 b (Empty String)
SELECT 2, SPACE(1) UNION ALL --1 b (1 space)
SELECT 3, SPACE(5) UNION ALL --1 b (5 spaces)
SELECT 4, ',' UNION ALL --2 b b (both are empty strings)
SELECT 5, '55555' UNION ALL --1 E
SELECT 6, ',55555' UNION ALL --2 b E
SELECT 7, ',55555,' UNION ALL --3 b E b
SELECT 8, '55555,' UNION ALL --2 b B
SELECT 9, '55555,1' UNION ALL --2 E E
SELECT 10, '1,55555' UNION ALL --2 E E
SELECT 11, '55555,4444,333,22,1' UNION ALL --5 E E E E E
SELECT 12, '55555,4444,,333,22,1' UNION ALL --6 E E b E E E
SELECT 13, ',55555,4444,,333,22,1,' UNION ALL --8 b E E b E E E b
SELECT 14, ',55555,4444,,,333,22,1,' UNION ALL --9 b E E b b E E E b
SELECT 15, ' 4444,55555 ' UNION ALL --2 E (w/Leading Space) E (w/Trailing Space)
SELECT 16, 'This,is,a,test.' --E E E E
) d (SomeID, SomeValue)
;
--===== Split the CSV column for the whole table using CROSS APPLY (this is the solution)
SELECT test.SomeID, test.SomeValue, split.ItemNumber, Item = QUOTENAME(split.Item,'"')
FROM #JBMTest test
CROSS APPLY dbo.DelimitedSplit8K(test.SomeValue,',') split
;
--=====================================================================================================================
-- TEST 2:
-- This tests for various "alpha" splits and COLLATION using all ASCII characters from 0 to 255 as a delimiter against
-- a given string. Note that not all of the delimiters will be visible and some will show up as tiny squares because
-- they are "control" characters. More specifically, this test will show you what happens to various non-accented
-- letters for your given collation depending on the delimiter you chose.
--=====================================================================================================================
WITH
cteBuildAllCharacters (String,Delimiter) AS
(
SELECT TOP 256
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
CHAR(ROW_NUMBER() OVER (ORDER BY (SELECT NULL))-1)
FROM master.sys.all_columns
)
SELECT ASCII_Value = ASCII(c.Delimiter), c.Delimiter, split.ItemNumber, Item = QUOTENAME(split.Item,'"')
FROM cteBuildAllCharacters c
CROSS APPLY dbo.DelimitedSplit8K(c.String,c.Delimiter) split
ORDER BY ASCII_Value, split.ItemNumber
;
-----------------------------------------------------------------------------------------------------------------------
Other Notes:
1. Optimized for VARCHAR(8000) or less. No testing or error reporting for truncation at 8000 characters is done.
2. Optimized for single character delimiter. Multi-character delimiters should be resolvedexternally from this
function.
3. Optimized for use with CROSS APPLY.
4. Does not "trim" elements just in case leading or trailing blanks are intended.
5. If you don't know how a Tally table can be used to replace loops, please see the following...
http://www.sqlservercentral.com/articles/T-SQL/62867/
6. Changing this function to use NVARCHAR(MAX) will cause it to run twice as slow. It's just the nature of
VARCHAR(MAX) whether it fits in-row or not.
7. Multi-machine testing for the method of using UNPIVOT instead of 10 SELECT/UNION ALLs shows that the UNPIVOT method
is quite machine dependent and can slow things down quite a bit.
-----------------------------------------------------------------------------------------------------------------------
Credits:
This code is the product of many people's efforts including but not limited to the following:
cteTally concept originally by Iztek Ben Gan and "decimalized" by Lynn Pettis (and others) for a bit of extra speed
and finally redacted by Jeff Moden for a different slant on readability and compactness. Hat's off to Paul White for
his simple explanations of CROSS APPLY and for his detailed testing efforts. Last but not least, thanks to
Ron "BitBucket" McCullough and Wayne Sheffield for their extreme performance testing across multiple machines and
versions of SQL Server. The latest improvement brought an additional 15-20% improvement over Rev 05. Special thanks
to "Nadrek" and "peter-757102" (aka Peter de Heer) for bringing such improvements to light. Nadrek's original
improvement brought about a 10% performance gain and Peter followed that up with the content of Rev 07.
I also thank whoever wrote the first article I ever saw on "numbers tables" which is located at the following URL
and to Adam Machanic for leading me to it many years ago.
-----------------------------------------------------------------------------------------------------------------------
Revision History:
Rev 00 - 20 Jan 2010 - Concept for inline cteTally: Lynn Pettis and others.
Redaction/Implementation: Jeff Moden
- Base 10 redaction and reduction for CTE. (Total rewrite)
Rev 01 - 13 Mar 2010 - Jeff Moden
- Removed one additional concatenation and one subtraction from the SUBSTRING in the SELECT List for that tiny
bit of extra speed.
Rev 02 - 14 Apr 2010 - Jeff Moden
- No code changes. Added CROSS APPLY usage example to the header, some additional credits, and extra
documentation.
Rev 03 - 18 Apr 2010 - Jeff Moden
- No code changes. Added notes 7, 8, and 9 about certain "optimizations" that don't actually work for this
type of function.
Rev 04 - 29 Jun 2010 - Jeff Moden
- Added WITH SCHEMABINDING thanks to a note by Paul White. This prevents an unnecessary "Table Spool" when the
function is used in an UPDATE statement even though the function makes no external references.
Rev 05 - 02 Apr 2011 - Jeff Moden
- Rewritten for extreme performance improvement especially for larger strings approaching the 8K boundary and
for strings that have wider elements. The redaction of this code involved removing ALL concatenation of
delimiters, optimization of the maximum "N" value by using TOP instead of including it in the WHERE clause,
and the reduction of all previous calculations (thanks to the switch to a "zero based" cteTally) to just one
instance of one add and one instance of a subtract. The length calculation for the final element (not
followed by a delimiter) in the string to be split has been greatly simplified by using the ISNULL/NULLIF
combination to determine when the CHARINDEX returned a 0 which indicates there are no more delimiters to be
had or to start with. Depending on the width of the elements, this code is between 4 and 8 times faster on a
single CPU box than the original code especially near the 8K boundary.
- Modified comments to include more sanity checks on the usage example, etc.
- Removed "other" notes 8 and 9 as they were no longer applicable.
Rev 06 - 12 Apr 2011 - Jeff Moden
- Based on a suggestion by Ron "Bitbucket" McCullough, additional test rows were added to the sample code and
the code was changed to encapsulate the output in pipes so that spaces and empty strings could be perceived
in the output. The first "Notes" section was added. Finally, an extra test was added to the comments above.
Rev 07 - 06 May 2011 - Peter de Heer, a further 15-20% performance enhancement has been discovered and incorporated
into this code which also eliminated the need for a "zero" position in the cteTally table.
**********************************************************************************************************************/
--===== Define I/O parameters
(@pString VARCHAR(8000), @pDelimiter CHAR(1))
RETURNS TABLE WITH SCHEMABINDING AS
RETURN
--===== "Inline" CTE Driven "Tally Table" produces values from 0 up to 10,000...
-- enough to cover NVARCHAR(4000)
WITH E1(N) AS (
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
), --10E+1 or 10 rows
E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
cteTally(N) AS (--==== This provides the "base" CTE and limits the number of rows right up front
-- for both a performance gain and prevention of accidental "overruns"
SELECT TOP (ISNULL(DATALENGTH(@pString),0)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
),
cteStart(N1) AS (--==== This returns N+1 (starting position of each "element" just once for each delimiter)
SELECT 1 UNION ALL
SELECT t.N+1 FROM cteTally t WHERE SUBSTRING(@pString,t.N,1) = @pDelimiter
),
cteLen(N1,L1) AS(--==== Return start and length (for use in substring)
SELECT s.N1,
ISNULL(NULLIF(CHARINDEX(@pDelimiter,@pString,s.N1),0)-s.N1,8000)
FROM cteStart s
)
--===== Do the actual split. The ISNULL/NULLIF combo handles the length for the final element when no delimiter is found.
SELECT ItemNumber = ROW_NUMBER() OVER(ORDER BY l.N1),
Item = SUBSTRING(@pString, l.N1, l.L1)
FROM cteLen l
;
GO
March 19, 2012 at 9:13 pm
Okay, pretty sure you've had the opportunity to see and test the code posted. Curious what you have found out testing it.
March 20, 2012 at 6:13 am
ya it was working fine
but why u and jef told don't use cursor
March 20, 2012 at 6:33 am
er.sivaganesh (3/20/2012)
ya it was working finebut why u and jef told don't use cursor
Three reasons for me...
1. They're usually slower than properly written set-based code. SQL Server works best when working with "sets" instead of individual rows. In fact, SQL Server didn't even have cursors until version 6.5. They were added to make certain types of processing much easier but a lot of people never actually need to do the type of processing that requires a cursor. They think so but there's usually a better way.
2. They're usually more resource hungry. If a cursor is used to update single rows, for example, it has to create or at least figure out that it needs to reuse one or more execution plans for every row.
3. They usually take more code to write than set based code does.
Not all cursors and While loops are bad. Just 99.9% of them. 🙂 If you really want to start writing high performance code, do like I recommend in my signature line below. Stop thinking about what you want to do to a row... think, instead, of what you want to do to a column."
--Jeff Moden
Change is inevitable... Change for the better is not.
March 20, 2012 at 7:04 am
er.sivaganesh (3/20/2012)
ya it was working finebut why u and jef told don't use cursor
To add to what Jeff said, cursors and while looks are row by row processing. It doesn't scale well as processing and data loads increase.
If you look at the code I posted you will not see any cursors or while loops in the stored procedure or the DelimitedSplit function (Jeff's function for spliting delimted strings, be sure to read all the comments and articles also linked in the comments).
Now, the question is, does the code posted do the same thing as your code written with a cursor?
March 21, 2012 at 11:31 pm
i just worked in your code it was working fine
and i dindnt compare the both result i will compare that too and i will tell u detaily
March 22, 2012 at 5:25 am
sorry to inform u that i am not getting correct output from your code
if i enter more than three words mean it shows all the value of the space id
plz wait i will tell u clearly after checking all the data
March 22, 2012 at 7:33 am
Well, you would have gotten tested code if you took the time to read and follow the instructions in the first article I reference in my signature block below regarding asking for help. Pretty sure that it was suggested in one of the threads you started for this problem.
If you provide the DDL for the tables, sample data for the tables, and the expected results based on the sample data we could actually test our possible solutions before posting them.
Without this information I can't debug my code.
March 22, 2012 at 7:38 am
Looking this thread, you can see again how important it is to follow "forum etiquette" and post DDL, sample data and expected results in most appropriate way when asking the question.
If not followed, its very often turns to be not only time-wasting exercise for helpers, but also for OP as well...
If still struggle: link at the bottom of my signature... 😎
Just another thought: should the screen, where you post your questions in, display the common message header from J Celko replies... :hehe:
March 22, 2012 at 11:44 pm
hi do u want the details of the tables which are connected in this query
Viewing 15 posts - 16 through 30 (of 47 total)
You must be logged in to reply to this topic. Login to reply