If i was to have a table with an integer column containing n number of rows and wanted to check if they were consecutive, how could I do this?
DECLARE @Temp TABLE
(
IntegerValue INT,
Processed BIT
)
I have a solution that works for 3 rows but this is infelxable, if the requirements chan开发者_高级运维ge then so would the query (ignoring the fact that my sum wouldnt work in this case).
@SumOfValues = (@FirstValue * @NumOfValues) + @NumOfValues
SELECT CASE
WHEN COUNT(DISTINCT IntegerValue) /*Or COUNT(*) dependant on how
duplicates should be treated */
= 1 + MAX(IntegerValue) - MIN(IntegerValue) THEN 'Y'
ELSE 'N'
END
FROM @Temp
If you want to know where the gaps are you can use
;WITH T AS
(
SELECT *,
DENSE_RANK() OVER (ORDER BY IntegerValue) - IntegerValue AS Grp
FROM @Temp
)
SELECT MIN(IntegerValue) AS RangeStart,
MAX(IntegerValue) AS RangeEnd
FROM T
GROUP BY Grp
ORDER BY MIN(IntegerValue)
CREATE TABLE #T(ID INT)
DECLARE @i INT
SET @I = 1
WHILE(@I <= LEN('12235588966'))
BEGIN
IF(SUBSTRING('12235588966',@i,1) = SUBSTRING('12235588966',@i-1,1))
BEGIN
INSERT INTO #T SELECT SUBSTRING('12235588966',@i,1)
END
SET @i = @I +1
END
SELECT * FROM #T
精彩评论