nicholas-ross / SSMS-Schema-Folders

This an extension for SQL Server Management Studio (SSMS). It groups sql objects in Object Explorer (tables, views, etc.) into schema folders.
GNU General Public License v2.0
162 stars 34 forks source link

Add feature to generate random table data by rightclick #28

Closed papyr closed 2 years ago

papyr commented 2 years ago

Hello this is very nice, any chance we could adopt this script/ C# class to populate any MsSQL table with Random Data.

// for e.g it would be helpful to do something like this. myPocoEntityTable.Filll(50).SkipFkeys(true);


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
nicholas-ross commented 2 years ago

This is out of scope for this project. SSMS already has a feature which should help you. Have a look at how to add and use code snippets. https://learn.microsoft.com/en-us/sql/ssms/scripting/transact-sql-code-snippets