Create test data in SQL Server

后端 未结 6 941
猫巷女王i
猫巷女王i 2021-02-05 20:50

Does anyone have or know of a SQL script that will generate test data for a given table?

Ideally it will look at the schema of the table and create row(s) with test data

6条回答
  •  不要未来只要你来
    2021-02-05 21:10

    We need step by step create query for tables need entry data. i used below codes, step by step for insert test data:

    1. Create a table :

    CREATE TABLE dbo.TestTableSize
    (
        MyKeyField VARCHAR(10) NOT NULL,
        MyDate1 DATETIME NOT NULL,
        MyDate2 DATETIME NOT NULL,
        MyDate3 DATETIME NOT NULL,
        MyDate4 DATETIME NOT NULL,
        MyDate5 DATETIME NOT NULL
    )
    

    2. Variable Declarations

    DECLARE @RowCount INT
    DECLARE @RowString VARCHAR(10)
    DECLARE @Random INT
    DECLARE @Upper INT
    DECLARE @Lower INT
    DECLARE @InsertDate DATETIME
    

    3.Set on time :

    SET @Lower = -730
    SET @Upper = -1
    SET @RowCount = 0
    

    4.Populate the Table :

    WHILE @RowCount < 3000000
    BEGIN
    

    5.Preparing Values

    SET @RowString = CAST(@RowCount AS VARCHAR(10))
    
        SELECT @Random = ROUND(((@Upper - @Lower -1) * RAND() + @Lower), 0)
    
        SET @InsertDate = DATEADD(dd, @Random, GETDATE())
    

    6. Write insert statment :

    INSERT INTO TestTableSize
            (MyKeyField
            ,MyDate1
            ,MyDate2
            ,MyDate3
            ,MyDate4
            ,MyDate5)
        VALUES
            (REPLICATE('0', 10 - DATALENGTH(@RowString)) + @RowString
            , @InsertDate
            ,DATEADD(dd, 1, @InsertDate)
            ,DATEADD(dd, 2, @InsertDate)
            ,DATEADD(dd, 3, @InsertDate)
            ,DATEADD(dd, 4, @InsertDate))
    
        SET @RowCount = @RowCount + 1
    END
    

    7. Complete code :

    DECLARE @RowCount INT
    DECLARE @RowString VARCHAR(10)
    DECLARE @Random INT
    DECLARE @Upper INT
    DECLARE @Lower INT
    DECLARE @InsertDate DATETIME
    
    SET @Lower = -730
    SET @Upper = -1
    SET @RowCount = 0
    
    WHILE @RowCount < 3000000
    BEGIN
        SET @RowString = CAST(@RowCount AS VARCHAR(10))
        SELECT @Random = ROUND(((@Upper - @Lower -1) * RAND() + @Lower), 0)
        SET @InsertDate = DATEADD(dd, @Random, GETDATE())
    
        INSERT INTO TestTableSize
            (MyKeyField
            ,MyDate1
            ,MyDate2
            ,MyDate3
            ,MyDate4
            ,MyDate5)
        VALUES
            (REPLICATE('0', 10 - DATALENGTH(@RowString)) + @RowString
            , @InsertDate
            ,DATEADD(dd, 1, @InsertDate)
            ,DATEADD(dd, 2, @InsertDate)
            ,DATEADD(dd, 3, @InsertDate)
            ,DATEADD(dd, 4, @InsertDate))
    
        SET @RowCount = @RowCount + 1
    END
    

提交回复
热议问题