Tuesday 25 July 2017

MSSQL - How to clear all caches?

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

/*
https://yabele.blogspot.com/2017/07/mssql-how-to-clear-all-caches.html
*/
SET NOCOUNT ON;
DECLARE @StartedAt DATETIME2 = GETDATE();
CHECKPOINT; 
DBCC DROPCLEANBUFFERS;
DBCC FREESYSTEMCACHE ('ALL');
-- Query
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:

IF OBJECT_ID(N'dbo.fn_extract_digits') IS NOT NULL
  DROP FUNCTION dbo.fn_extract_digits;
GO

CREATE FUNCTION dbo.fn_extract_digits (@str VARCHAR(MAX))
/*
https://yabele.blogspot.com/2017/07/mssql-t-sql-equivalent-of-vba-val.html
*/
RETURNS INT
AS
BEGIN
  DECLARE
    @newstr VARCHAR(MAX) = '',
    @i INT = 1,
    @chr CHAR(1);

  WHILE @i <= LEN(@str) BEGIN
    SET @chr = SUBSTRING(@str, @i, 1);
    IF @chr BETWEEN '0' AND '9'
      SET @newstr = @newstr + @chr;
    SET @i = @i + 1;
  END;

  RETURN CAST(@newstr AS INT);
END
/*
DECLARE @str VARCHAR(MAX) = '1-23-456';
SELECT Digits = dbo.fn_extract_digits(@str);*/
;

MSSQL - Function to generate empty rows

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

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