在 SQL Server 中创建测试数据

2023-12-19

有谁拥有或知道可以为给定表生成测试数据的 SQL 脚本吗?

理想情况下,它将查看表的架构,并根据每列的数据类型创建包含测试数据的行。

如果这个不存在,其他人会觉得它有用吗?如果是这样,我会抽出手指写一篇。


好吧,我想我应该抽出手指给自己写一个轻量级数据生成器:

declare @select varchar(max), @insert varchar(max), @column varchar(100),
    @type varchar(100), @identity bit, @db nvarchar(100)

set @db = N'Orders'
set @select = 'select '
set @insert = 'insert into ' + @db + ' ('


declare crD cursor fast_forward for
select column_name, data_type, 
COLUMNPROPERTY(
    OBJECT_ID(
       TABLE_SCHEMA + '.' + TABLE_NAME), 
    COLUMN_NAME, 'IsIdentity') AS COLUMN_ID
from Northwind.INFORMATION_SCHEMA.COLUMNS
where table_name = @db


open crD
fetch crD into @column, @type, @identity

while @@fetch_status = 0
begin
if @identity = 0 or @identity is null
begin
    set @insert = @insert + @column + ', ' 
    set @select = @select  + 
        case @type
            when 'int' then '1'
            when 'varchar' then '''test'''
            when 'nvarchar' then '''test'''
            when 'smalldatetime' then 'getdate()'
            when 'bit' then '0'
            else 'NULL'
        end + ', ' 
end
fetch crD into @column, @type, @identity
end 

set @select = left(@select, len(@select) - 1)
set @insert = left(@insert, len(@insert) - 1) + ')'
exec(@insert + @select)

close crD
deallocate crD

给定任何表,脚本将创建一个记录,其中包含一些任意类型值; int、varchar、nvarchar、smalldatetime 和位。 case 语句可以用函数替换。它不会向下移动依赖项,但会跳过任何种子列。

我创建这个的动机是针对一个包含 50 列的表测试我的 NHibernate 映射文件,因此我需要一个可以重复使用的快速简单脚本。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 SQL Server 中创建测试数据 的相关文章

随机推荐