2012-11-22 47 views

回答

85

1-打開SQL Server Management Studio。

2-右鍵單擊包含所需表的數據庫。

3-選擇「任務=>生成腳本...」。

4-按照嚮導,選擇要爲其生成腳本的對象(表,視圖,存儲過程等)。

5從下一步,點擊「高級」,併爲標記爲「數據腳本類型」節點選擇「架構和數據」。

enter image description here

6-保存腳本和微笑:)

3

爲此,您可以使用生成腳本的數據庫任務。 右鍵單擊數據庫>任務>生成腳本... 選擇「選擇特定數據庫對象」和所需表格。

在「設置腳本選項」頁面上,單擊「高級」。 有一個選項「腳本數據的類型」,選擇「模式和數據」。選擇保存位置。下一個。下一個。完。

但是,如果表中包含大量數據,我建議使用bcp out或其他方法導出數據。如果新服務器位於同一網絡上,則也可以將其選爲鏈接服務器。

腳本方法將生成單獨的插入語句。

4
select 'create table [' + so.name + '] (' + o.list + ')' + CASE WHEN tc.Constraint_Name IS NULL THEN '' ELSE 'ALTER TABLE ' + so.Name + ' ADD CONSTRAINT ' + tc.Constraint_Name + ' PRIMARY KEY ' + ' (' + LEFT(j.List, Len(j.List)-1) + ')' END 
from sysobjects so 
cross apply 
    (SELECT 
     ' ['+column_name+'] ' + 
     data_type + case data_type 
      when 'sql_variant' then '' 
      when 'text' then '' 
      when 'ntext' then '' 
      when 'xml' then '' 
      when 'decimal' then '(' + cast(numeric_precision as varchar) + ', ' + cast(numeric_scale as varchar) + ')' 
      else coalesce('('+case when character_maximum_length = -1 then 'MAX' else cast(character_maximum_length as varchar) end +')','') end + ' ' + 
     case when exists ( 
     select id from syscolumns 
     where object_name(id)=so.name 
     and name=column_name 
     and columnproperty(id,name,'IsIdentity') = 1 
     ) then 
     'IDENTITY(' + 
     cast(ident_seed(so.name) as varchar) + ',' + 
     cast(ident_incr(so.name) as varchar) + ')' 
     else '' 
     end + ' ' + 
     (case when IS_NULLABLE = 'No' then 'NOT ' else '' end) + 'NULL ' + 
      case when information_schema.columns.COLUMN_DEFAULT IS NOT NULL THEN 'DEFAULT '+ information_schema.columns.COLUMN_DEFAULT ELSE '' END + ', ' 

    from information_schema.columns where table_name = so.name 
    order by ordinal_position 
    FOR XML PATH('')) o (list) 
left join 
    information_schema.table_constraints tc 
on tc.Table_name  = so.Name 
AND tc.Constraint_Type = 'PRIMARY KEY' 
cross apply 
    (select '[' + Column_Name + '], ' 
    FROM information_schema.key_column_usage kcu 
    WHERE kcu.Constraint_Name = tc.Constraint_Name 
    ORDER BY 
     ORDINAL_POSITION 
    FOR XML PATH('')) j (list) 
where xtype = 'U' 
AND name NOT IN ('dtproperties') 
相關問題