In SQL Server, how do I generate a CREATE TABLE statement for a given table?

前端 未结 16 2199
离开以前
离开以前 2020-11-22 11:34

I\'ve spent a good amount of time coming up with solution to this problem, so in the spirit of this post, I\'m posting it here, since I think it might be useful to others. <

16条回答
  •  盖世英雄少女心
    2020-11-22 11:58

    -- or you could create a stored procedure ... first with Id creation

    USE [db]
    GO
    
    /****** Object:  StoredProcedure [dbo].[procUtils_InsertGeneratorWithId]    Script Date: 06/13/2009 22:18:11 ******/
    SET ANSI_NULLS ON
    GO
    
    SET QUOTED_IDENTIFIER ON
    GO
    
    
    create PROC [dbo].[procUtils_InsertGeneratorWithId]    
    (    
    @domain_user varchar(50),    
    @tableName varchar(100)    
    )     
    
    
    as    
    
    --Declare a cursor to retrieve column specific information for the specified table    
    DECLARE cursCol CURSOR FAST_FORWARD FOR     
    SELECT column_name,data_type FROM information_schema.columns WHERE table_name = @tableName    
    OPEN cursCol    
    DECLARE @string nvarchar(3000) --for storing the first half of INSERT statement    
    DECLARE @stringData nvarchar(3000) --for storing the data (VALUES) related statement    
    DECLARE @dataType nvarchar(1000) --data types returned for respective columns    
    DECLARE @IDENTITY_STRING nvarchar ( 100 )    
    SET @IDENTITY_STRING = ' '     
    select  @IDENTITY_STRING    
    SET @string='INSERT '+@tableName+'('    
    SET @stringData=''    
    
    DECLARE @colName nvarchar(50)    
    
    FETCH NEXT FROM cursCol INTO @colName,@dataType    
    
    IF @@fetch_status<>0    
     begin    
     print 'Table '+@tableName+' not found, processing skipped.'    
     close curscol    
     deallocate curscol    
     return    
    END    
    
    WHILE @@FETCH_STATUS=0    
    BEGIN    
    IF @dataType in ('varchar','char','nchar','nvarchar')    
    BEGIN    
     --SET @stringData=@stringData+'''''''''+isnull('+@colName+','''')+'''''',''+'    
     SET @stringData=@stringData+''''+'''+isnull('''''+'''''+'+@colName+'+'''''+''''',''NULL'')+'',''+'    
    END    
    ELSE    
    if @dataType in ('text','ntext') --if the datatype is text or something else     
    BEGIN    
     SET @stringData=@stringData+'''''''''+isnull(cast('+@colName+' as varchar(2000)),'''')+'''''',''+'    
    END    
    ELSE    
    IF @dataType = 'money' --because money doesn't get converted from varchar implicitly    
    BEGIN    
     SET @stringData=@stringData+'''convert(money,''''''+isnull(cast('+@colName+' as varchar(200)),''0.0000'')+''''''),''+'    
    END    
    ELSE     
    IF @dataType='datetime'    
    BEGIN    
     --SET @stringData=@stringData+'''convert(datetime,''''''+isnull(cast('+@colName+' as varchar(200)),''0'')+''''''),''+'    
     --SELECT 'INSERT Authorizations(StatusDate) VALUES('+'convert(datetime,'+isnull(''''+convert(varchar(200),StatusDate,121)+'''','NULL')+',121),)' FROM Authorizations    
     --SET @stringData=@stringData+'''convert(money,''''''+isnull(cast('+@colName+' as varchar(200)),''0.0000'')+''''''),''+'    
     SET @stringData=@stringData+'''convert(datetime,'+'''+isnull('''''+'''''+convert(varchar(200),'+@colName+',121)+'''''+''''',''NULL'')+'',121),''+'    
      --                             'convert(datetime,'+isnull(''''+convert(varchar(200),StatusDate,121)+'''','NULL')+',121),)' FROM Authorizations    
    END    
    ELSE     
    IF @dataType='image'     
    BEGIN    
     SET @stringData=@stringData+'''''''''+isnull(cast(convert(varbinary,'+@colName+') as varchar(6)),''0'')+'''''',''+'    
    END    
    ELSE --presuming the data type is int,bit,numeric,decimal     
    BEGIN    
     --SET @stringData=@stringData+'''''''''+isnull(cast('+@colName+' as varchar(200)),''0'')+'''''',''+'    
     --SET @stringData=@stringData+'''convert(datetime,'+'''+isnull('''''+'''''+convert(varchar(200),'+@colName+',121)+'''''+''''',''NULL'')+'',121),''+'    
     SET @stringData=@stringData+''''+'''+isnull('''''+'''''+convert(varchar(200),'+@colName+')+'''''+''''',''NULL'')+'',''+'    
    END    
    
    SET @string=@string+@colName+','    
    
    FETCH NEXT FROM cursCol INTO @colName,@dataType    
    END    
    DECLARE @Query nvarchar(4000)    
    
    SET @query ='SELECT '''+substring(@string,0,len(@string)) + ') VALUES(''+ ' + substring(@stringData,0,len(@stringData)-2)+'''+'')'' FROM '+@tableName    
    exec sp_executesql @query    
    --select @query    
    
    CLOSE cursCol    
    DEALLOCATE cursCol    
    
    
      /*
    USAGE
    
    */
    
    GO
    

    -- and second without iD INSERTION

    USE [db]
    GO
    
    /****** Object:  StoredProcedure [dbo].[procUtils_InsertGenerator]    Script Date: 06/13/2009 22:20:52 ******/
    SET ANSI_NULLS ON
    GO
    
    SET QUOTED_IDENTIFIER ON
    GO
    
    CREATE PROC [dbo].[procUtils_InsertGenerator]        
    (        
    @domain_user varchar(50),        
    @tableName varchar(100)        
    )         
    
    
    as        
    
    --Declare a cursor to retrieve column specific information for the specified table        
    DECLARE cursCol CURSOR FAST_FORWARD FOR         
    
    
    -- SELECT column_name,data_type FROM information_schema.columns WHERE table_name = @tableName        
    /* NEW     
    SELECT c.name , sc.data_type  FROM sys.extended_properties AS ep                   
    INNER JOIN sys.tables AS t ON ep.major_id = t.object_id                   
    INNER JOIN sys.columns AS c ON ep.major_id = c.object_id AND ep.minor_id                   
    = c.column_id                   
    INNER JOIN INFORMATION_SCHEMA.COLUMNS sc ON t.name = sc.table_name and                   
    c.name = sc.column_name                   
    WHERE t.name = @tableName and c.is_identity=0      
      */      
    
    select object_name(c.object_id) "TABLE_NAME", c.name "COLUMN_NAME", s.name "DATA_TYPE"      
      from sys.columns c          
      join sys.systypes s on (s.xtype = c.system_type_id)          
      where object_name(c.object_id) in (select name from sys.tables where name not like 'sysdiagrams')          
       AND object_name(c.object_id) in (select name from sys.tables where [name]=@tableName  ) and c.is_identity=0 and s.name not like 'sysname'  
    
    
    
    
    OPEN cursCol        
    DECLARE @string nvarchar(3000) --for storing the first half of INSERT statement        
    DECLARE @stringData nvarchar(3000) --for storing the data (VALUES) related statement        
    DECLARE @dataType nvarchar(1000) --data types returned for respective columns        
    DECLARE @IDENTITY_STRING nvarchar ( 100 )        
    SET @IDENTITY_STRING = ' '         
    select  @IDENTITY_STRING        
    SET @string='INSERT '+@tableName+'('        
    SET @stringData=''        
    
    DECLARE @colName nvarchar(50)        
    
    FETCH NEXT FROM cursCol INTO @tableName , @colName,@dataType        
    
    IF @@fetch_status<>0        
     begin        
     print 'Table '+@tableName+' not found, processing skipped.'        
     close curscol        
     deallocate curscol        
     return        
    END        
    
    WHILE @@FETCH_STATUS=0        
    BEGIN        
    IF @dataType in ('varchar','char','nchar','nvarchar')        
    BEGIN        
     --SET @stringData=@stringData+'''''''''+isnull('+@colName+','''')+'''''',''+'        
     SET @stringData=@stringData+''''+'''+isnull('''''+'''''+'+@colName+'+'''''+''''',''NULL'')+'',''+'        
    END        
    ELSE        
    if @dataType in ('text','ntext') --if the datatype is text or something else         
    BEGIN        
     SET @stringData=@stringData+'''''''''+isnull(cast('+@colName+' as varchar(2000)),'''')+'''''',''+'        
    END        
    ELSE        
    IF @dataType = 'money' --because money doesn't get converted from varchar implicitly        
    BEGIN        
     SET @stringData=@stringData+'''convert(money,''''''+isnull(cast('+@colName+' as varchar(200)),''0.0000'')+''''''),''+'        
    END        
    ELSE         
    IF @dataType='datetime'        
    BEGIN        
     --SET @stringData=@stringData+'''convert(datetime,''''''+isnull(cast('+@colName+' as varchar(200)),''0'')+''''''),''+'        
     --SELECT 'INSERT Authorizations(StatusDate) VALUES('+'convert(datetime,'+isnull(''''+convert(varchar(200),StatusDate,121)+'''','NULL')+',121),)' FROM Authorizations        
     --SET @stringData=@stringData+'''convert(money,''''''+isnull(cast('+@colName+' as varchar(200)),''0.0000'')+''''''),''+'        
     SET @stringData=@stringData+'''convert(datetime,'+'''+isnull('''''+'''''+convert(varchar(200),'+@colName+',121)+'''''+''''',''NULL'')+'',121),''+'        
      --                             'convert(datetime,'+isnull(''''+convert(varchar(200),StatusDate,121)+'''','NULL')+',121),)' FROM Authorizations        
    END        
    ELSE         
    IF @dataType='image'         
    BEGIN        
     SET @stringData=@stringData+'''''''''+isnull(cast(convert(varbinary,'+@colName+') as varchar(6)),''0'')+'''''',''+'        
    END        
    ELSE --presuming the data type is int,bit,numeric,decimal         
    BEGIN        
     --SET @stringData=@stringData+'''''''''+isnull(cast('+@colName+' as varchar(200)),''0'')+'''''',''+'        
     --SET @stringData=@stringData+'''convert(datetime,'+'''+isnull('''''+'''''+convert(varchar(200),'+@colName+',121)+'''''+''''',''NULL'')+'',121),''+'        
     SET @stringData=@stringData+''''+'''+isnull('''''+'''''+convert(varchar(200),'+@colName+')+'''''+''''',''NULL'')+'',''+'        
    END        
    
    SET @string=@string+@colName+','        
    
    FETCH NEXT FROM cursCol INTO @tableName , @colName,@dataType        
    END        
    DECLARE @Query nvarchar(4000)        
    
    SET @query ='SELECT '''+substring(@string,0,len(@string)) + ') VALUES(''+ ' + substring(@stringData,0,len(@stringData)-2)+'''+'')'' FROM '+@tableName        
    exec sp_executesql @query        
    --select @query       
    
    CLOSE cursCol        
    DEALLOCATE cursCol        
    
    
      /*      
    
    use poc     
    go    
    
    DECLARE @RC int      
    DECLARE @domain_user varchar(50)      
    DECLARE @tableName varchar(100)      
    
    -- TODO: Set parameter values here.      
    set @domain_user='yorgeorg'      
    set @tableName = 'tbGui_WizardTabButtonAreas'      
    
    EXECUTE @RC = [POC].[dbo].[procUtils_InsertGenerator]       
       @domain_user      
      ,@tableName      
    
    */
    GO
    

提交回复
热议问题