I have to insert a specific number of rows into a SQL Server table.
DECLARE @val AS INT = 20,
@val2 AS VARCHAR(50),
@Date AS DATETIME = CONVER
You could use a recursive CTE.
DECLARE @i INT = 1
, @m INT = 19
, @d DATETIME2 = '2016-05-02';
WITH i AS (
SELECT 0 AS increment
UNION ALL
SELECT i.increment + @i
FROM i
WHERE i.increment < @m
)
SELECT i.increment
, DATEADD(DAY, i.increment, @d)
FROM i
OPTION (MAXRECURSION 100);
Note the OPTION (MAXRECUSION 100) hint at the bottom, which is not strictly necessary but I have included it to illustrate how it works. By default, there is a limit of 100 results using this method, so without this statement and if @m were a large number e.g. 1000 then SQL would generate an error. You can set the lmit to 0 which means unbounded, but only do this after testing your code, because it can get stuck in an infinite loop this way (which is why the limit exists by default).