Automatically generate a user defined table type that matches an existing table

后端 未结 3 1249
清酒与你
清酒与你 2021-02-14 01:04

I have several tables that already exist in my database. Some of them have quite a few columns.

I want to make some stored procedures to do a merge statement with these

3条回答
  •  不知归路
    2021-02-14 01:51

    I need the same thing from time to time. Here's a small script I put together. It's a bit rough and I wouldn't trust it with my life, but it works reasonably well for my case. It doesn't script keys, but for my scenario that's not necessary. I'm on SQL 2012 though, so I'm not completely sure this will work as is on SQL 2008. I did not test it for some of the more 'exotic' types like geometry, geography and friends, as I never needed to use them.

    declare
        @tablename nvarchar(50)='Users',
        @schemaname nvarchar(50)='dbo',
        @sql nvarchar(max)=N'';
    
    select @sql += N',' + NCHAR(13) + NCHAR(10) + NCHAR(9) + N'[' + c.COLUMN_NAME + N'] [' + DATA_TYPE + N']'
        + case when c.CHARACTER_MAXIMUM_LENGTH is not null then N'(' + case c.CHARACTER_MAXIMUM_LENGTH when -1 then 'max' else cast(c.CHARACTER_MAXIMUM_LENGTH as nvarchar(10)) end + N')' else N'' end
        + case when c.DATA_TYPE = N'numeric' then N'('+CAST(NUMERIC_PRECISION as nvarchar(10))+N', '+CAST(NUMERIC_SCALE as nvarchar(10))+N')' else N'' end
        + case when c.is_nullable <> N'NO' then N' NULL' else N' NOT NULL'end
    from INFORMATION_SCHEMA.COLUMNS c
    where TABLE_NAME = @tablename AND TABLE_SCHEMA = @schemaname
    order by ORDINAL_POSITION;
    
    set @sql = stuff(@sql, 1, 1, N'CREATE TYPE [' + @schemaname + N'].[tab_' + @tablename + N'] AS TABLE(')
        + nchar(13) + nchar(10) + ')' + nchar(13) + nchar(10) + 'GO';
    set @sql += nchar(13) + nchar(10) + '--GRANT EXEC ON TYPE::[' + @schemaname + N'].[tab_' + @tablename + N'] TO [User];'
        + nchar(13) + nchar(10) + '--GO';
    
    print @sql
    -- If you're happy with the sql, you can pass it to sp_executesql to create your type
    -- exec sp_executesql @sql;
    

提交回复
热议问题