如何在sql server中按表名获取sql查询脚本

时间:2018-02-21 11:53:43

标签: sql sql-server

这里在sql server中我希望通过表名获取sql脚本,在mysql服务器中有SHOW CREATE TABLE client的选项,任何人都可以帮助我们如何通过脚本在sql server中执行此操作?

3 个答案:

答案 0 :(得分:3)

CREATE PROCEDURE [dbo].[GENERATE_INSERTS] (@TABLENAME      NVARCHAR(100),
                                           @INCLUDE_COLUMN VARCHAR(MAX)=NULL,
                                           @EXCLUDE_COLUMN VARCHAR(MAX) = NULL,
                                           @TOP            varchar(50)='',
                                           @WHERECLAUSE    NVARCHAR(MAX) = '',
                                           @ORDERBYCLAUSE  NVARCHAR(MAX) = '')
AS
  BEGIN
      SET NOCOUNT ON
      --DECLARE VARIABLES
      DECLARE @TABLEHASIDENTITY BIT
      DECLARE @SQL NVARCHAR(MAX)
      DECLARE @COLUMNLIST NVARCHAR(MAX)
      DECLARE @VALUELIST NVARCHAR(MAX)
      DECLARE @COLUMN_NAME VARCHAR(128)
      DECLARE @DATA_TYPE VARCHAR(128)

      --INITIALIZE VARIABLES
      SET @COLUMNLIST = ''
      SET @VALUELIST = ''
      SET @COLUMN_NAME = ''

      --CHECK IF THE TABLE HAS AN IDENTITY COLUMN
      SELECT @TABLEHASIDENTITY = OBJECTPROPERTY(OBJECT_ID(TABLE_NAME), 'TABLEHASIDENTITY')
      FROM   INFORMATION_SCHEMA.TABLES
      WHERE  TABLE_NAME = @TABLENAME

      --CHECK IF WE NEED 'SET IDENTITY_INSERT TABLENAME ON' STATEMENT.
      --IF THE TABLE HAS IDENTITY COLUMN, THE IDENTITY_INSERT WILL BE SET TO ON
      IF @TABLEHASIDENTITY = 1
        BEGIN
            SET @SQL = 'SELECT TOP 1 ''SET IDENTITY_INSERT '
                       + @TABLENAME + ' ON '' FROM ' + @TABLENAME

            EXEC SP_EXECUTESQL
              @SQL
        END

      --PREPARE LIST OF COLUMNS AND VALUES
      --TO GET THE FIRST COLUMN'S ID



          DECLARE NA_CUR CURSOR LOCAL FAST_FORWARD FOR
            SELECT QUOTENAME(COLUMN_NAME),
                   DATA_TYPE from
INFORMATION_SCHEMA.COLUMNS C (NOLOCK)
      WHERE  TABLE_NAME = @TABLENAME
             AND (EXISTS (SELECT TOKEN
                                   FROM   DBO.UDF_SPLITSTRING(@INCLUDE_COLUMN, ',') A WHERE C.TABLE_NAME=A.token )
             --AND ( COLUMN_NAME IN (SELECT TOKEN
             --                      FROM   DBO.UDF_SPLITSTRING(@INCLUDE_COLUMN, ','))
                    OR @INCLUDE_COLUMN IS NULL  or @INCLUDE_COLUMN= '')
             AND ( NOT EXISTS (SELECT 1
                               FROM   DBO.UDF_SPLITSTRING(@EXCLUDE_COLUMN, ',') F
                               WHERE  F.TOKEN = C.COLUMN_NAME)
                    OR @EXCLUDE_COLUMN IS NULL or @EXCLUDE_COLUMN = ''  )


            ORDER  BY ORDINAL_POSITION ASC 

          OPEN NA_CUR

          FETCH NA_CUR INTO @COLUMN_NAME, @DATA_TYPE

          WHILE @@FETCH_STATUS = 0
            BEGIN





            --DETERMINING THE DATA TYPE OF THE COLUMN AND DEPENDING ON THE DATA TYPE, 
            --THE VALUES PART OF THE INSERT STATEMENT IS GENERATED.
            SET @VALUELIST = @VALUELIST + CASE  WHEN @DATA_TYPE IN ('CHAR', 'VARCHAR', 'NCHAR', 'NVARCHAR') THEN 'COALESCE('''''''' + REPLACE(RTRIM(' + @COLUMN_NAME + '),'''''''','''''''''''')+'''''''',''NULL'')' 
                                                WHEN @DATA_TYPE IN ('DATETIME', 'SMALLDATETIME') THEN 'COALESCE('''''''' + RTRIM(CONVERT(CHAR,' + @COLUMN_NAME + ',109))+'''''''',''NULL'')' 
                                                WHEN @DATA_TYPE IN ('UNIQUEIDENTIFIER') THEN 'COALESCE('''''''' + REPLACE(CONVERT(CHAR(255),RTRIM(' + @COLUMN_NAME + ')),'''''''','''''''''''')+'''''''',''NULL'')' 
                                                WHEN @DATA_TYPE IN ('TEXT', 'NTEXT') THEN 'COALESCE('''''''' + REPLACE(CONVERT(CHAR(8000),' + @COLUMN_NAME + '),'''''''','''''''''''')+'''''''',''NULL'')' 
                                                WHEN @DATA_TYPE IN ('BINARY', 'VARBINARY') THEN 'COALESCE(RTRIM(CONVERT(CHAR,' + 'CONVERT(INT,' + @COLUMN_NAME + '))),''NULL'')' 
                                                WHEN @DATA_TYPE IN ('TIMESTAMP', 'ROWVERSION') THEN 'COALESCE(RTRIM(CONVERT(CHAR,' + 'CONVERT(INT,' + @COLUMN_NAME + '))),''NULL'')' 
                                                WHEN @DATA_TYPE IN ('FLOAT', 'REAL', 'MONEY', 'SMALLMONEY') THEN 'COALESCE(LTRIM(RTRIM(' + 'CONVERT(CHAR, ' + @COLUMN_NAME + ',2)' + ')),''NULL'')' 
                             ELSE 'COALESCE(LTRIM(RTRIM(' + 'CONVERT(CHAR, ' + @COLUMN_NAME + ')' + ')),''NULL'')' END + '+' + ''',''' + ' + '
            --GENERATING THE COLUMN LIST FOR THE INSERT STATEMENT
            SET @COLUMNLIST = @COLUMNLIST + @COLUMN_NAME + ','

            PRINT @COLUMNLIST
            PRINT @VALUELIST


           FETCH NA_CUR INTO @COLUMN_NAME, @DATA_TYPE
            END

          CLOSE NA_CUR;

          DEALLOCATE NA_CUR;


      --END OF LOOP
      --REMOVE EXTRA CHARACTERS THAT GOT CONCATENATED DURING THE LAST RUN THROUGH THE LOOP
      SET @COLUMNLIST = LEFT(@COLUMNLIST, LEN(@COLUMNLIST) - 1)
      SET @VALUELIST = LEFT(@VALUELIST, LEN(@VALUELIST) - 6)

      print @COLUMNLIST
      PRINT @VALUELIST
      set @top = case when len(@top)>0 then 'top '+@TOP else '' end
      --BUILD THE SQL STATEMENT
      SET @SQL = 'SELECT '+@top+'''INSERT INTO [' + @TABLENAME + '] ('
                 + @COLUMNLIST + ') ' + 'VALUES (''+' + @VALUELIST
                 + '+'')'' FROM ' + @TABLENAME

      --APPLY FILTER (WHERE CLAUSE) AND SORTING (ORDER BY CLAUSE) IF REQUIRED
      IF LEN(@WHERECLAUSE) > 0
        SET @SQL = @SQL + ' WHERE ' + @WHERECLAUSE

      IF LEN(@ORDERBYCLAUSE) > 0
        SET @SQL= @SQL + ' ORDER BY ' + @ORDERBYCLAUSE

      --EXECUTE SQL STATEMENT TO PRINT INSERT STATEMENTS
      PRINT @SQL       
      EXEC SP_EXECUTESQL
        @SQL

      --SET IDENTITY_INSERT OFF IF IT IS SET ON ABOVE
      IF @TABLEHASIDENTITY = 1
        BEGIN
            SET @SQL = 'SELECT TOP 1 ''SET IDENTITY_INSERT '
                       + @TABLENAME + ' OFF '' FROM ' + @TABLENAME

            EXEC SP_EXECUTESQL
              @SQL
        END
  END 

答案 1 :(得分:1)

我认为最简单的方法是使用SQL Server Management studio并使用Generate Scripts功能。

更多信息:https://docs.microsoft.com/en-us/sql/relational-databases/scripting/generate-scripts-sql-server-management-studio

希望它有所帮助。

编辑:

用户反馈后:

Lowell Izaguirre写了一个可能对你有帮助的剧本。它可以在此链接http://www.sqlservercentral.com/scripts/SQL+Server+2005/67515/

中的SQLServerCentral上找到

答案 2 :(得分:0)

来自Here,希望它会有所帮助。

CREATE proc GetTableScript (@table sysname)
as
declare @sql table(s varchar(1000), id int identity)


insert into  @sql(s) values ('create table [' + @table + '] (')


insert into @sql(s)
select 
    '  ['+column_name+'] ' + 
    data_type + coalesce('('+cast(character_maximum_length as varchar)+')','') + ' ' +
    case when exists ( 
        select id from syscolumns
        where object_name(id)=@table
        and name=column_name
        and columnproperty(id,name,'IsIdentity') = 1 
    ) then
        'IDENTITY(' + 
        cast(ident_seed(@table) as varchar) + ',' + 
        cast(ident_incr(@table) as varchar) + ')'
    else ''
    end + ' ' +
    ( case when IS_NULLABLE = 'No' then 'NOT ' else '' end ) + 'NULL ' + 
    coalesce('DEFAULT '+COLUMN_DEFAULT,'') + ','

 from information_schema.columns where table_name = @table
 order by ordinal_position


declare @pkname varchar(100)
select @pkname = constraint_name from information_schema.table_constraints
where table_name = @table and constraint_type='PRIMARY KEY'

if ( @pkname is not null ) begin
    insert into @sql(s) values('  PRIMARY KEY (')
    insert into @sql(s)
        select '   ['+COLUMN_NAME+'],' from information_schema.key_column_usage
        where constraint_name = @pkname
        order by ordinal_position

    update @sql set s=left(s,len(s)-1) where id=@@identity
    insert into @sql(s) values ('  )')
end
else begin

    update @sql set s=left(s,len(s)-1) where id=@@identity
end

insert into @sql(s) values( ')' )

select s from @sql order by id