Tuesday, 25 July 2017

MSSQL - How to clear all caches?

Script to clear all caches? (For example for performance debug)

  1. /*
  2. https://yabele.blogspot.com/2017/07/mssql-how-to-clear-all-caches.html
  3. */
  4. SET NOCOUNT ON;
  5. DECLARE @StartedAt DATETIME2 = GETDATE();
  6. CHECKPOINT;
  7. DBCC DROPCLEANBUFFERS;
  8. DBCC FREESYSTEMCACHE ('ALL');
  9. -- Query
  10. PRINT ' Elapsed time: ' + CAST(DATEDIFF(ms, @StartedAt, GETDATE()) AS VarChar(20)) + ' ms';

MSSQL - T-SQL equivalent of VBA VAL() function

There the text of scalar-value function to extract numbers from string and convert to integer:

  1. IF OBJECT_ID(N'dbo.fn_extract_digits') IS NOT NULL
  2. DROP FUNCTION dbo.fn_extract_digits;
  3. GO
  4.  
  5. CREATE FUNCTION dbo.fn_extract_digits (@str VARCHAR(MAX))
  6. /*
  7. https://yabele.blogspot.com/2017/07/mssql-t-sql-equivalent-of-vba-val.html
  8. */
  9. RETURNS INT
  10. AS
  11. BEGIN
  12. DECLARE
  13. @newstr VARCHAR(MAX) = '',
  14. @i INT = 1,
  15. @chr CHAR(1);
  16.  
  17. WHILE @i <= LEN(@str) BEGIN
  18. SET @chr = SUBSTRING(@str, @i, 1);
  19. IF @chr BETWEEN '0' AND '9'
  20. SET @newstr = @newstr + @chr;
  21. SET @i = @i + 1;
  22. END;
  23.  
  24. RETURN CAST(@newstr AS INT);
  25. END
  26. /*
  27. DECLARE @str VARCHAR(MAX) = '1-23-456';
  28. SELECT Digits = dbo.fn_extract_digits(@str);*/
  29. ;

MSSQL - Function to generate empty rows

There the text of inline table-value function to generate a specified count of empty rows:

  1. IF OBJECT_ID(N'dbo.GenerateRows') IS NOT NULL
  2. DROP FUNCTION dbo.GenerateRows;
  3. GO
  4. CREATE FUNCTION dbo.GenerateRows (@Count INT)
  5. /*
  6. https://yabele.blogspot.com/2017/07/mssql-function-to-generate-empty-rows.html
  7. */
  8. RETURNS TABLE
  9. AS
  10. RETURN
  11. WITH TenRows AS (
  12. SELECT * FROM (VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9),(10)) AS T(I)
  13. )
  14. SELECT TOP(@Count)
  15. I = ROW_NUMBER() OVER(ORDER BY (SELECT 1))
  16. FROM
  17. TenRows T1 CROSS JOIN TenRows T2 CROSS JOIN TenRows T3 CROSS JOIN TenRows T4 CROSS JOIN TenRows T5
  18. /*
  19. SELECT * FROM dbo.GenerateRows(100);
  20. */
  21. ;