|
|
|
Grasshopper
      
Group: General Forum Members
Last Login: Friday, April 05, 2013 9:42 AM
Points: 11,
Visits: 26
|
|
Hi all,
I am looking at a table which holds a record of things typed by different users into a field in our front end. It looks something a bit like this:
UserName Time FieldValue Bob Hope 12:00:00 We cannot do anything until 1 O'Clock - the penguin needs defrosting Rolf Harris 13:00:00 We cannot do anything until 1 O'Clock - the penguin needs defrosting I have defrosted it Jeff Bridges 13:13:00 We cannot do anything until 1 O'Clock - the penguin needs defrosting I have defrosted it It's Alive! Jenny Bond 13:46:25 We cannot do anything until 1 O'Clock - the penguin needs defrosting I have defrosted it It's Alive! I let it go.
The basic format is that text is never removed; each new entry is appended on to the end of the last entry in a new row on the table (presumably this enables the history function to work for users in the front end). My problem is that when I produce a report of all the messages in the field, I only want to list the addition that each person made:
UserName Time FieldValue Bob Hope 12:00:00 We cannot do anything until 1 O'Clock - the penguin needs defrosting Rolf Harris 13:00:00 I have defrosted it Jeff Bridges 13:13:00 It's Alive! Jenny Bond 13:46:25 I let it go.
Given that the Field value is stared as a text datatype and it is conceivable that the total message length may exceed 8000 characters, is there any way to achieve what I want? If I start using substrings etc, I will limit myself to 8000 characters, even when using a VARCHAR(MAX) (At least I think that is the case..?)
Any help much appreciated, as I am beginning to pull my hair... Thanks Mark
|
|
|
|
|
SSCertifiable
       
Group: General Forum Members
Last Login: Today @ 9:27 AM
Points: 5,618,
Visits: 10,990
|
|
-- sample data DROP TABLE #Sample CREATE TABLE #Sample (UserName VARCHAR(15), [Time] CHAR(8), FieldValue TEXT) INSERT INTO #Sample (UserName, [Time], FieldValue) SELECT 'Bob Hope', '12:00:00', 'We cannot do anything until 1 O''Clock - the penguin needs defrosting' UNION ALL SELECT 'Rolf Harris', '13:00:00', 'We cannot do anything until 1 O''Clock - the penguin needs defrosting I have defrosted it' UNION ALL SELECT 'Jeff Bridges', '13:13:00', 'We cannot do anything until 1 O''Clock - the penguin needs defrosting I have defrosted it It''s Alive!' UNION ALL SELECT 'Jenny Bond', '13:46:25', 'We cannot do anything until 1 O''Clock - the penguin needs defrosting I have defrosted it It''s Alive! I let it go.'
-- solution ;WITH SequencedData AS ( SELECT UserName, [Time], FieldValue = CAST(FieldValue AS VARCHAR(MAX)), rn = ROW_NUMBER() OVER (ORDER BY [Time]) FROM #Sample ), rCTE AS ( SELECT UserName, [Time], rn, UserString = FieldValue, FieldValue = FieldValue FROM SequencedData WHERE rn = 1 UNION ALL SELECT tr.UserName, tr.[Time], tr.rn, UserString = LTRIM(REPLACE(tr.FieldValue,lr.FieldValue,'')), FieldValue = tr.FieldValue FROM SequencedData tr INNER JOIN rCTE lr ON lr.rn+1 = tr.rn ) SELECT UserName, [Time], UserString FROM rCTE
“Write the query the simplest way. If through testing it becomes clear that the performance is inadequate, consider alternative query forms.” - Gail Shaw
For fast, accurate and documented assistance in answering your questions, please read this article. Understanding and using APPLY, (I) and (II) Paul White Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden Exploring Recursive CTEs by Example Dwain Camps
|
|
|
|
|
SSCoach
         
Group: General Forum Members
Last Login: 2 days ago @ 1:55 PM
Points: 15,442,
Visits: 9,571
|
|
Another possible:
IF OBJECT_ID(N'tempdb..#T') IS NOT NULL DROP TABLE #T; CREATE TABLE #T (EntryID INT NOT NULL, EntryTime DATETIME NOT NULL, FieldValue VARCHAR(MAX));
INSERT INTO #T (EntryID, EntryTime, FieldValue) VALUES (1, '20120924 00:00:00', 'We cannot do anything until 1 O''Clock - the penguin needs defrosting'), (1, '20120924 13:00:00', 'We cannot do anything until 1 O''Clock - the penguin needs defrosting I have defrosted it'), (1, '20120924 13:05:00', 'We cannot do anything until 1 O''Clock - the penguin needs defrosting I have defrosted it It''s Alive!'), (1, '20120924 13:10:00', 'We cannot do anything until 1 O''Clock - the penguin needs defrosting I have defrosted it It''s Alive! I let it go.');
SELECT T1.EntryTime, LTRIM(STUFF(T1.FieldValue, 1, ISNULL(LEN(Previous.FieldValue), 0), '')) FROM #T AS T1 OUTER APPLY (SELECT TOP (1) * FROM #T AS T2 WHERE T1.EntryID = T2.EntryID AND T1.EntryTime > T2.EntryTime ORDER BY EntryTime DESC) AS Previous ORDER BY T1.EntryTime; Outer Apply grabs the immediately prior row, if any, gets the Len() of the value, and uses Stuff() to get rid of that much of the beginning of the string.
Using Replace() (as per Chris idea), might not work if a string can repeat itself inside the data. If, for example, the first entry were "Hello!", and the second were then "Hello! Hello! to you too", you'd end up with the "Hello!" substring stripped out where it's not supposed to be. If that's not a possible scenario (repeating string), then it won't matter and either will work.
- Gus "GSquared", RSVP, OODA, MAP, NMVP, FAQ, SAT, SQL, DNA, RNA, UOI, IOU, AM, PM, AD, BC, BCE, USA, UN, CF, ROFL, LOL, ETC Property of The Thread
"Nobody knows the age of the human race, but everyone agrees it's old enough to know better." - Anon
|
|
|
|
|
SSCrazy Eights
        
Group: General Forum Members
Last Login: Today @ 2:33 PM
Points: 8,620,
Visits: 8,261
|
|
Hi and welcome to SSC. It is difficult to answer your question because there is not a lot of detail in the question. From your description I am pretty sure that you can accomplish this. You just need to find the text of the "previous" entry and replace that with ''.
create table #SomeData ( UserName varchar(20), EntryTime Time, FieldValue varchar(max) )
insert #SomeData select 'Bob Hope', '12:00:00', 'We cannot do anything until 1 O''Clock - the penguin needs defrosting' union all select 'Rolf Harris', '13:00:00', 'We cannot do anything until 1 O''Clock - the penguin needs defrosting I have defrosted it' union all select 'Jeff Bridges', '13:13:00', 'We cannot do anything until 1 O''Clock - the penguin needs defrosting I have defrosted it It''s Alive!' union all select 'Jenny Bond', '13:46:25', 'We cannot do anything until 1 O''Clock - the penguin needs defrosting I have defrosted it It''s Alive! I let it go.'
;with cte as ( select *, ROW_NUMBER()over(order by EntryTime) as RowNum from #SomeData ) , cte2 as ( SELECT UserName, EntryTime, c1.FieldValue as FieldValue1, c1.RowNum, (select c2.FieldValue from cte c2 where c2.RowNum = c1.RowNum - 1) as FieldValue2 FROM cte c1 )
select UserName, EntryTime, ltrim(isnull(REPLACE(FieldValue1, FieldValue2, ''), FieldValue1)) as NewValue from cte2
drop table #SomeData
Notice how I posted sample data and structures. This is something you should consider on future posts. You can view the first link in my signature for best practices when posting questions.
--EDIT--
LOL it seems that two others posted while I was writing my response.
_______________________________________________________________
Need help? Help us help you.
Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.
Need to split a string? Try Jeff Moden's splitter.
Cross Tabs and Pivots, Part 1 – Converting Rows to Columns Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs
|
|
|
|
|
SSCrazy Eights
        
Group: General Forum Members
Last Login: Today @ 2:33 PM
Points: 8,620,
Visits: 8,261
|
|
|
|
|
|
Grasshopper
      
Group: General Forum Members
Last Login: Friday, April 05, 2013 9:42 AM
Points: 11,
Visits: 26
|
|
Thanks Chris and GSquared for replies and speed!
I see how those work; my concern is that using things like REPLACE(),LEN(),LEFT() on a text field of more than 8000 characters will truncate the length down to 8000 characters, meaning that I could lose data off the end of my fieldvalue; the example below will return 8000:
DECLARE @String VARCHAR(MAX) = REPLICATE('a',10000) SELECT LEN(@String)
I am using SQL Server 2008 R2, so the VARCHAR(MAX) should be able to hold something like 2^31 characters
Edit: Wow - you post faster than I do! I hear you about the need for sample data - taken on board. Unfortunately, we are using a database built by an external software company and have no real control over the format.
|
|
|
|
|
SSCertifiable
       
Group: General Forum Members
Last Login: Today @ 9:27 AM
Points: 5,618,
Visits: 10,990
|
|
GSquared (9/24/2012)
Another possible: IF OBJECT_ID(N'tempdb..#T') IS NOT NULL DROP TABLE #T; CREATE TABLE #T (EntryID INT NOT NULL, EntryTime DATETIME NOT NULL, FieldValue VARCHAR(MAX));
INSERT INTO #T (EntryID, EntryTime, FieldValue) VALUES (1, '20120924 00:00:00', 'We cannot do anything until 1 O''Clock - the penguin needs defrosting'), (1, '20120924 13:00:00', 'We cannot do anything until 1 O''Clock - the penguin needs defrosting I have defrosted it'), (1, '20120924 13:05:00', 'We cannot do anything until 1 O''Clock - the penguin needs defrosting I have defrosted it It''s Alive!'), (1, '20120924 13:10:00', 'We cannot do anything until 1 O''Clock - the penguin needs defrosting I have defrosted it It''s Alive! I let it go.');
SELECT T1.EntryTime, LTRIM(STUFF(T1.FieldValue, 1, ISNULL(LEN(Previous.FieldValue), 0), '')) FROM #T AS T1 OUTER APPLY (SELECT TOP (1) * FROM #T AS T2 WHERE T1.EntryID = T2.EntryID AND T1.EntryTime > T2.EntryTime ORDER BY EntryTime DESC) AS Previous ORDER BY T1.EntryTime; Outer Apply grabs the immediately prior row, if any, gets the Len() of the value, and uses Stuff() to get rid of that much of the beginning of the string. Using Replace() (as per Chris idea), might not work if a string can repeat itself inside the data. If, for example, the first entry were "Hello!", and the second were then "Hello! Hello! to you too", you'd end up with the "Hello!" substring stripped out where it's not supposed to be. If that's not a possible scenario (repeating string), then it won't matter and either will work.
Good point, Gus. First mental pass used STUFF but it flew away during coding.
-- sample data DROP TABLE #Sample CREATE TABLE #Sample (UserName VARCHAR(15), [Time] CHAR(8), FieldValue TEXT) INSERT INTO #Sample (UserName, [Time], FieldValue) SELECT 'Bob Hope', '12:00:00', 'We cannot do anything until 1 O''Clock - the penguin needs defrosting' UNION ALL SELECT 'Rolf Harris', '13:00:00', 'We cannot do anything until 1 O''Clock - the penguin needs defrosting I have defrosted it' UNION ALL SELECT 'Jeff Bridges', '13:13:00', 'We cannot do anything until 1 O''Clock - the penguin needs defrosting I have defrosted it It''s Alive!' UNION ALL SELECT 'Jenny Bond', '13:46:25', 'We cannot do anything until 1 O''Clock - the penguin needs defrosting I have defrosted it It''s Alive! I let it go.'
-- solution ;WITH SequencedData AS ( SELECT UserName, [Time], FieldValue = CAST(FieldValue AS VARCHAR(MAX)), rn = ROW_NUMBER() OVER (ORDER BY [Time]) FROM #Sample ), rCTE AS ( SELECT UserName, [Time], rn, UserString = FieldValue, FieldValue = FieldValue FROM SequencedData WHERE rn = 1 UNION ALL SELECT tr.UserName, tr.[Time], tr.rn, UserString = LTRIM(STUFF(tr.FieldValue,1,DATALENGTH(lr.FieldValue),'')), FieldValue = tr.FieldValue FROM SequencedData tr INNER JOIN rCTE lr ON lr.rn+1 = tr.rn ) SELECT UserName, [Time], UserString FROM rCTE
“Write the query the simplest way. If through testing it becomes clear that the performance is inadequate, consider alternative query forms.” - Gail Shaw
For fast, accurate and documented assistance in answering your questions, please read this article. Understanding and using APPLY, (I) and (II) Paul White Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden Exploring Recursive CTEs by Example Dwain Camps
|
|
|
|
|
SSCertifiable
       
Group: General Forum Members
Last Login: Today @ 9:27 AM
Points: 5,618,
Visits: 10,990
|
|
High Plains Grifter (9/24/2012) Thanks Chris and GSquared for replies and speed!
I see how those work; my concern is that using things like REPLACE(),LEN(),LEFT() on a text field of more than 8000 characters will truncate the length down to 8000 characters, meaning that I could lose data off the end of my fieldvalue; the example below will return 8000:
DECLARE @String VARCHAR(MAX) = REPLICATE('a',10000) SELECT LEN(@String)
I am using SQL Server 2008 R2, so the VARCHAR(MAX) should be able to hold something like 2^31 characters
Edit: Wow - you post faster than I do! I hear you about the need for sample data - taken on board. Unfortunately, we are using a database built by an external software company and have no real control over the format.
DECLARE @String VARCHAR(MAX) = REPLICATE(CAST('a' AS VARCHAR(MAX)),10000) SELECT LEN(@String)
“Write the query the simplest way. If through testing it becomes clear that the performance is inadequate, consider alternative query forms.” - Gail Shaw
For fast, accurate and documented assistance in answering your questions, please read this article. Understanding and using APPLY, (I) and (II) Paul White Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden Exploring Recursive CTEs by Example Dwain Camps
|
|
|
|
|
Grasshopper
      
Group: General Forum Members
Last Login: Friday, April 05, 2013 9:42 AM
Points: 11,
Visits: 26
|
|
| Ok... Magic? I guess that one needs a google; I cannot explain that by looking!
|
|
|
|
|
SSCertifiable
       
Group: General Forum Members
Last Login: Today @ 9:27 AM
Points: 5,618,
Visits: 10,990
|
|
|
|
|