根据数据生成 INSERT INTO ... 的 SQL (.Net C#, T-SQL Store Procedure 分别实现)

/*
今天看了 昨天 灵感的 随笔:
http://unruledboy.cnblogs.com/archive/2005/07/18/SmartDBScripts.html

类似的工具也曾写过,今天拿出改改,重新分享给大家!

1. .Net 1.1 C# 实现
这仅仅是一个命令行工具,根据指定的 SQL Select 查询:
select * from Table
来生成 insert into ... 的 SQL

生成的 SQL 的 列之间使用 "\t" Tab 分割,
这样生成的 SQL, Copy & Paste 到 Excel 中,利于编辑,很轻松就可以删掉不想要的列

另外还可以控制是否处理 二进制 的大字段!

实现方式使用 DataSet 和 DataReader 两种方法重载!
区别是:

DataReader.GetDataTypeName(i) 方法可以得到 native 的 SQL Server 的数据类型

DataReader.GetFieldType(i) 方法
DataSet 的 DataTable 的 DataColumn.DataType 属性

都只能得到 .Net 的数据类型!

完整程序下载
http://files.cnblogs.com/Microshaoft/SqlGen.cs.rar

2. T-SQL Store Procedure 实现
有局限性,数据量太大无法生成完整正确的 insert into .... SQL!
*/

1. .Net C#

ExpandedBlockStart.gif ContractedBlock.gif /**/ /*
InBlock.gif编译命令行
InBlock.gifcsc.exe noname1.cs /r:C:\WINdows\Microsoft.NET\Framework\v1.1.4322\System.Data.OracleClient.dll
ExpandedBlockEnd.gif
*/

None.gif
None.gif
namespace  Microshaoft.ApplicationTest
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
using Microshaoft.Util;
InBlock.gif    
using Microshaoft.Data;
InBlock.gif
InBlock.gif    
using System;
InBlock.gif    
using System.Data;
InBlock.gif    
using System.Data.SqlClient;
InBlock.gif
InBlock.gif    
public class ConsoleApplication
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
static string bs = ""//用于记录上次的位数
InBlock.gif
        static int j = 0;
InBlock.gif
InBlock.gif        [STAThread] 
//应 ClipBoard 需要
InBlock.gif
        public static void Main(string[] args)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
//                System.Console.WriteLine("pls enter Server:");
InBlock.gif            
//                string S = System.Console.ReadLine();
InBlock.gif            
//        
InBlock.gif            
//                System.Console.WriteLine("pls enter DataBase:");
InBlock.gif            
//                string D = System.Console.ReadLine();
InBlock.gif            
//        
InBlock.gif            
//                System.Console.WriteLine("pls enter User:");
InBlock.gif            
//                string U = System.Console.ReadLine();
InBlock.gif            
//        
InBlock.gif            
//                System.Console.WriteLine("pls enter Password:");
InBlock.gif            
//                string P = System.Console.ReadLine();
InBlock.gif            
//        
InBlock.gif            
//                System.Console.WriteLine("pls enter SQL:");
InBlock.gif            
//                string sql = System.Console.ReadLine();
InBlock.gif            
//
InBlock.gif
InBlock.gif            
// DataReader
InBlock.gif
            string sql = "select * from province";
InBlock.gif            
string ConnectionString;
InBlock.gif            
//ConnectionString = @"Server=" + S + ";Database=" + D + ";User ID=" + U + ";Password=" + P;
InBlock.gif
            ConnectionString = @"Server=192.168.1.7\vnet3dev;Database=vnet3center;User ID=vnetdev;password=vnetdev";
InBlock.gif            
string s = "";
InBlock.gif
InBlock.gif            
//下面引用 Microsoft SqlHelper 得到 SqlDataReader
InBlock.gif
            SqlDataReader x = SqlHelper.ExecuteReader(ConnectionString, System.Data.CommandType.Text, sql);
InBlock.gif
InBlock.gif            InsertInToSQLGenerator.RowRetrived 
+= new Microshaoft.Util.InsertInToSQLGenerator.RowEventHandler(InsertInToSQLGenerator_RowRetrived);
InBlock.gif
InBlock.gif            System.Console.WriteLine(
"\nuse SqlDataReader :");
InBlock.gif            System.Console.Write(
"正在进行第    ");
InBlock.gif            s 
= InsertInToSQLGenerator.Generate(x, true);
InBlock.gif            
//System.Windows.Forms.Clipboard.SetDataObject(s, true);
InBlock.gif
InBlock.gif            
InBlock.gif            
//System.Console.ReadLine();
InBlock.gif
            sw.WriteLine("\n");
InBlock.gif
InBlock.gif
//            j = 0;
InBlock.gif
//            // DataSet
InBlock.gif
//            System.Data.SqlClient.SqlConnection sc = new System.Data.SqlClient.SqlConnection(ConnectionString);
InBlock.gif
//            //下面引用 Microsoft SqlHelper 得到 DataSet
InBlock.gif
//            //DataSet ds = SqlHelper.ExecuteDataset(sc, System.Data.CommandType.Text, sql);
InBlock.gif
//            SqlParameter [] spa = SqlHelperParameterCache.GetSpParameterSet(sc,"zsp_calendar");
InBlock.gif
//            spa[0].Value = System.DateTime.Parse("1995-09-09");
InBlock.gif
//            DataSet ds = SqlHelper.ExecuteDataset(sc,CommandType.StoredProcedure,"zsp_calendar",spa);
InBlock.gif
//            System.Console.WriteLine("\nuse DataSet :");
InBlock.gif
//            System.Console.Write("正在进行第    ");
InBlock.gif
//            bs = "";
InBlock.gif
//            s = InsertInToSQLGenerator.Generate(ds, true);
InBlock.gif            
//System.Windows.Forms.Clipboard.SetDataObject(s, true);
InBlock.gif

InBlock.gif            sw.Close();
InBlock.gif            sw 
= null;
InBlock.gif
InBlock.gif            System.Console.WriteLine(
"\nPress any key to continue dot.gif");
InBlock.gif            
//System.Console.WriteLine("\n" + s);
InBlock.gif

InBlock.gif            System.Console.ReadLine();
InBlock.gif
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
static System.IO.StreamWriter sw = new System.IO.StreamWriter("Output.sql"false, System.Text.Encoding.GetEncoding("gb2312"));
InBlock.gif
InBlock.gif        
private static void InsertInToSQLGenerator_RowRetrived(string tableName, string fieldNameList, string fieldValueList)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            sw.WriteLine(
"INSERT INTO \t[" + tableName + "]\t (\t" + fieldNameList + "\t) VALUES (\t" + fieldValueList + "\t)");
InBlock.gif            System.Console.Write(bs 
+ "\b\b\b" + +++ " 次," + System.DateTime.Now);
InBlock.gif            bs 
= new string('\b', Digits(j) + System.DateTime.Now.ToString().Length + 1); //19 为日期时间字符串长度, 1 是 ","
ExpandedSubBlockEnd.gif
        }

InBlock.gif
InBlock.gif        
public static int Digits(int n) //数字所占位数
ExpandedSubBlockStart.gifContractedSubBlock.gif
        dot.gif{
InBlock.gif            n 
= System.Math.Abs(n);
InBlock.gif            n 
= n/10;
InBlock.gif            
int i = 1;
InBlock.gif            
while (n > 0)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                n 
= n/10;
InBlock.gif                i
++;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
return i;
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif
None.gif
// ================================================================================================================
None.gif

None.gif
namespace  Microshaoft.Util
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
using System.Data;
InBlock.gif    
public class InsertInToSQLGenerator
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
public delegate void RowEventHandler(string TableName,string FieldNameList,string FieldValueList);
InBlock.gif        
public static event RowEventHandler RowRetrived;
InBlock.gif
InBlock.gif        
public static string Generate(DataSet ds, bool IgnoreBigColumn)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            System.Text.StringBuilder sb 
= new System.Text.StringBuilder();
InBlock.gif            
foreach (DataTable dt in ds.Tables)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
bool b = true;
InBlock.gif                
if (sb.Length > 0)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    sb.Append(
"\n");
ExpandedSubBlockEnd.gif                }

InBlock.gif                
string s = "";
InBlock.gif                
foreach (DataRow dr in dt.Rows)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
string r = "";
InBlock.gif                    
if (sb.Length > 0)
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        sb.Append(
"\n");
ExpandedSubBlockEnd.gif                    }

InBlock.gif                    
foreach (DataColumn dc in dt.Columns)
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        
string f = "";
InBlock.gif                        
switch (dc.DataType.FullName)
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
dot.gif{
InBlock.gif                            
case "System.Boolean" :
InBlock.gif                                f 
= dr[dc] == System.DBNull.Value ? "Null" : ((bool) dr[dc]) ? "1" : "0";
InBlock.gif                                
break;
InBlock.gif                            
case "System.Decimal" :
InBlock.gif                                
goto case "System.Int32";
InBlock.gif                            
case "System.Double" :
InBlock.gif                                
goto case "System.Int32";
InBlock.gif                            
case "System.Int16" :
InBlock.gif                                
goto case "System.Int32";
InBlock.gif                            
case "System.Int64" :
InBlock.gif                                
goto case "System.Int32";
InBlock.gif                            
case "System.Single" :
InBlock.gif                                
goto case "System.Int32";
InBlock.gif                            
case "System.UInt16" :
InBlock.gif                                
goto case "System.Int32";
InBlock.gif                            
case "System.UInt32" :
InBlock.gif                                
goto case "System.Int32";
InBlock.gif                            
case "System.UInt64" :
InBlock.gif                                
goto case "System.Int32";
InBlock.gif                            
case "System.Int32" :
InBlock.gif                                f 
= dr[dc] == System.DBNull.Value ? "Null" : dr[dc].ToString();
InBlock.gif                                
break;
InBlock.gif                            
case "System.Char" :
InBlock.gif                                
goto case "System.String";
InBlock.gif                            
case "System.DateTime" :
InBlock.gif                                
goto case "System.String";
InBlock.gif                            
case "System.String" :
InBlock.gif                                f 
= dr[dc] == System.DBNull.Value ? "Null" : "'" + dr[dc].ToString().Replace("'""''").Replace("\n""' + CHAR(13) + '"+ "'";
InBlock.gif                                
break;
InBlock.gif                            
default:
InBlock.gif                                
if (!IgnoreBigColumn)
ExpandedSubBlockStart.gifContractedSubBlock.gif                                
dot.gif{
InBlock.gif                                    f 
= "Null";
ExpandedSubBlockEnd.gif                                }

InBlock.gif                                
break;
ExpandedSubBlockEnd.gif                        }

InBlock.gif                        
if (f != "")
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
dot.gif{
InBlock.gif                            
if (r != "")
ExpandedSubBlockStart.gifContractedSubBlock.gif                            
dot.gif{
InBlock.gif                                r 
+= "\t,";
InBlock.gif                                
if (b)
ExpandedSubBlockStart.gifContractedSubBlock.gif                                
dot.gif{
InBlock.gif                                    s 
+= "\t,";
ExpandedSubBlockEnd.gif                                }

ExpandedSubBlockEnd.gif                            }

InBlock.gif                            r 
+= f;
InBlock.gif                            
if (b)
ExpandedSubBlockStart.gifContractedSubBlock.gif                            
dot.gif{
InBlock.gif                                s 
+= "[" + dc.ColumnName + "]";
ExpandedSubBlockEnd.gif                            }

ExpandedSubBlockEnd.gif                        }

ExpandedSubBlockEnd.gif                    }

InBlock.gif                    
string sql = "INSERT INTO \t[" + dt.TableName + "]\t (\t" + s + "\t) VALUES (\t" + r + "\t)";
InBlock.gif                    
if (RowRetrived != null)
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        RowRetrived(dt.TableName, s, r);
ExpandedSubBlockEnd.gif                    }

InBlock.gif                    sb.Append(sql);
InBlock.gif                    b 
= false;
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif            
return sb.ToString();
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
public static string Generate(IDataReader idr, bool IgnoreBigColumn)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            System.Text.StringBuilder sb 
= new System.Text.StringBuilder();
InBlock.gif            
int k = 0;
InBlock.gif            
do
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
bool b = true;
InBlock.gif                
if (sb.Length > 0)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    sb.Append(
"\n");
ExpandedSubBlockEnd.gif                }

InBlock.gif                
string s = "";
InBlock.gif                
while (idr.Read())
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
string r = "";
InBlock.gif                    
if (sb.Length > 0)
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        sb.Append(
"\n");
ExpandedSubBlockEnd.gif                    }

InBlock.gif                    
for (int i = 0; i < idr.FieldCount; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        
string f = "";
InBlock.gif
//                        注释掉的代码只适用于 SQL Server
InBlock.gif
//                        switch (idr.GetDataTypeName(i))
InBlock.gif
//                        {
InBlock.gif
//                            case "bit" :
InBlock.gif
//                                f = idr.IsDBNull(i) ? "Null" : ((bool) idr[i]) ? "1" : "0";
InBlock.gif
//                                break;
InBlock.gif
//                            case "bigint" :
InBlock.gif
//                                goto case "int";
InBlock.gif
//                            case "smallint" :
InBlock.gif
//                                goto case "int";
InBlock.gif
//                            case "tinyint" :
InBlock.gif
//                                goto case "int";
InBlock.gif
//                            case "decimal" :
InBlock.gif
//                                goto case "int";
InBlock.gif
//                            case "numeric" :
InBlock.gif
//                                goto case "int";
InBlock.gif
//                            case "money" :
InBlock.gif
//                                goto case "int";
InBlock.gif
//                            case "smallmoney" :
InBlock.gif
//                                goto case "int";
InBlock.gif
//                            case "float" :
InBlock.gif
//                                goto case "int";
InBlock.gif
//                            case "real" :
InBlock.gif
//                                goto case "int";
InBlock.gif
//                            case "int" :
InBlock.gif
//                                f = idr.IsDBNull(i) ? "Null" : idr[i].ToString();
InBlock.gif
//                                break;
InBlock.gif
//                            case "datetime" :
InBlock.gif
//                                goto case "varchar";
InBlock.gif
//                            case "smalldatetime" :
InBlock.gif
//                                goto case "varchar";
InBlock.gif
//                            case "char" :
InBlock.gif
//                                goto case "varchar";
InBlock.gif
//                            case "text" :
InBlock.gif
//                                goto case "varchar";
InBlock.gif
//                            case "varchar" :
InBlock.gif
//                                f = idr.IsDBNull(i) ? "Null" : "'" + idr[i].ToString().Replace("'", "''") + "'";
InBlock.gif
//                                break;
InBlock.gif
//                            case "nchar" :
InBlock.gif
//                                goto case "nvarchar";
InBlock.gif
//                            case "ntext" :
InBlock.gif
//                                goto case "nvarchar";
InBlock.gif
//                            case "nvarchar" :
InBlock.gif
//                                f = idr.IsDBNull(i) ? "Null" : "N'" + idr[i].ToString().Replace("'", "''") + "'";
InBlock.gif
//                                break;
InBlock.gif
//                            default:
InBlock.gif
//                                if (!IgnoreBigColumn)
InBlock.gif
//                                {
InBlock.gif
//                                    f = "Null";
InBlock.gif
//                                }
InBlock.gif
//                                break;
InBlock.gif
//                        }
InBlock.gif
                        switch (idr.GetFieldType(i).FullName)
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
dot.gif{
InBlock.gif                            
case "System.Boolean" :
InBlock.gif                                f 
= idr.IsDBNull(i) ? "Null" : ((bool) idr[i]) ? "1" : "0";
InBlock.gif                                
break;
InBlock.gif                            
case "System.Decimal" :
InBlock.gif                                
goto case "System.Int32";
InBlock.gif                            
case "System.Double" :
InBlock.gif                                
goto case "System.Int32";
InBlock.gif                            
case "System.Int16" :
InBlock.gif                                
goto case "System.Int32";
InBlock.gif                            
case "System.Int64" :
InBlock.gif                                
goto case "System.Int32";
InBlock.gif                            
case "System.Single" :
InBlock.gif                                
goto case "System.Int32";
InBlock.gif                            
case "System.UInt16" :
InBlock.gif                                
goto case "System.Int32";
InBlock.gif                            
case "System.UInt32" :
InBlock.gif                                
goto case "System.Int32";
InBlock.gif                            
case "System.UInt64" :
InBlock.gif                                
goto case "System.Int32";
InBlock.gif                            
case "System.Int32" :
InBlock.gif                                f 
= idr.IsDBNull(i) ? "Null" : idr[i].ToString();
InBlock.gif                                
break;
InBlock.gif                            
case "System.Char" :
InBlock.gif                                
goto case "System.String";
InBlock.gif                            
case "System.DateTime" :
InBlock.gif                                
goto case "System.String";
InBlock.gif                            
case "System.String" :
InBlock.gif                                f 
= idr.IsDBNull(i) ? "Null" : "'" + idr[i].ToString().Replace("'""''").Replace("\n","' + CHAR(13) + '"+ "'";
InBlock.gif                                
break;
InBlock.gif                            
default:
InBlock.gif                                
if (!IgnoreBigColumn)
ExpandedSubBlockStart.gifContractedSubBlock.gif                                
dot.gif{
InBlock.gif                                    f 
= "Null";
ExpandedSubBlockEnd.gif                                }

InBlock.gif                                
break;
ExpandedSubBlockEnd.gif                        }

InBlock.gif                        
if (f != "")
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
dot.gif{
InBlock.gif                            
if (r != "")
ExpandedSubBlockStart.gifContractedSubBlock.gif                            
dot.gif{
InBlock.gif                                r 
+= "\t,";
InBlock.gif                                
if (b)
ExpandedSubBlockStart.gifContractedSubBlock.gif                                
dot.gif{
InBlock.gif                                    s 
+= "\t,";
ExpandedSubBlockEnd.gif                                }

ExpandedSubBlockEnd.gif                            }

InBlock.gif                            r 
+= f;
InBlock.gif                            
if (b)
ExpandedSubBlockStart.gifContractedSubBlock.gif                            
dot.gif{
InBlock.gif                                s 
+= "[" + idr.GetName(i) + "]";
ExpandedSubBlockEnd.gif                            }

ExpandedSubBlockEnd.gif                        }

ExpandedSubBlockEnd.gif                    }

InBlock.gif                    b 
= false;
InBlock.gif                    
string sql = "INSERT INTO \t[Table" + k + "]\t (\t" + s + "\t) VALUES (\t" + r + "\t)";
InBlock.gif                    
if (RowRetrived != null)
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        RowRetrived(
"Table" + k, s, r);
ExpandedSubBlockEnd.gif                    }

InBlock.gif                    sb.Append(sql);
ExpandedSubBlockEnd.gif                }

InBlock.gif                k 
++;
ExpandedSubBlockEnd.gif            }
 while (idr.NextResult());
InBlock.gif            
return sb.ToString();
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif
None.gif
// ================================================================================================================
None.gif
None.gif
//  下面是 Microsoft SqlHelper :
None.gif
None.gif
// Data Access Application Block 3.1
None.gif
//   http://www.gotdotnet.com/workspaces/workspace.aspx?id=c20d12b0-af52-402b-9b7c-aaeb21d1f431
None.gif
//  SqlHelper.v3.1.cs
None.gif
// csc.exe SqlHelper.v3.1.cs /t:library /r:C:\WINNT\Microsoft.NET\Framework\v1.1.4322\System.Data.OracleClient.dll
None.gif

 


2. T-SQL Store Procedure 实现
有局限性,如果字段太多无法生成完整正确的 Select 'insert into ....' 的 SQL!

None.gif create    proc  Z_SP_GenInsertSQL ( @tablename   varchar ( 256 ))
None.gif
as
None.gif
begin
None.gif  
declare   @sql   varchar ( 8000 )
None.gif  
declare   @sqlValues   varchar ( 8000 )
None.gif  
set   @sql   = '  ( '   +   char ( 9 )
None.gif  
set   @sqlValues   =   ' values  ' +   char ( 9 +   ' ( '   +   char ( 9 +   ''' + '
None.gif  
select   @sqlValues   =   @sqlValues   +  cols  +   '  +  '' , '   +   char ( 9 +   '''  +  '   , @sql   =   @sql   +   ' [ '   +  name  +   ' ], '   +   CHAR ( 9 )
None.gif    
from  
None.gif        (
select   case  
None.gif                  
when  xtype  in  ( 48 , 52 , 56 , 59 , 60 , 62 , 104 , 106 , 108 , 122 , 127 )                                
None.gif                       
then   ' case when  ' +  name  + '  is null then  '' NULL ''  else  '   +   ' cast( ' +  name  +   '  as varchar) ' + '  end '
None.gif                  
when  xtype  in  ( 58 , 61 )
None.gif                       
then   ' case when  ' +  name  + '  is null then  '' NULL ''  else  ' + '''''''''  +  '   +   ' cast( ' +  name  + '  as varchar) ' +   ' + ''''''''' + '  end '
None.gif                  
when  xtype  in  ( 167 , 175 )
None.gif                       
then   ' case when  ' +  name  + '  is null then  '' NULL ''  else  ' + '''''''''  +  '   +   ' replace( ' +  name + ' , '''''''' , '''''''''''' ) '   +   ' + '''''''''   +   '  end '
None.gif                  
when  xtype  in  ( 231 , 239 )
None.gif                       
then   ' case when  ' +  name  + '  is null then  '' NULL ''  else  ' + ''' N ''''''  +  '   +   ' replace( ' +  name + ' , '''''''' , '''''''''''' ) '   +   ' + '''''''''   +   '  end '
None.gif                  
else   ''' NULL '''
None.gif                
end   as  Cols,name
None.gif           
from  syscolumns  
None.gif          
where  id  =   object_id ( @tablename and  autoval  is   null
None.gif        ) T 
None.gif  
set   @sql   = ' select  '' INSERT INTO  '   +   CHAR ( 9 +   ' [ ' +   @tablename   +   ' ] '   +   CHAR ( 9 +   left ( @sql , len ( @sql ) - 2 +   char ( 9 +   ' '    +   CHAR ( 9 +   left ( @sqlValues , len ( @sqlValues ) - 5 +   char ( 9 +   ' ) ''  from  ' + @tablename
None.gif  
print   @sql
None.gif  
exec  ( @sql )
ExpandedBlockStart.gifContractedBlock.gif
/**/ /*
InBlock.gifselect *
InBlock.giffrom syscolumns  
InBlock.gifwhere id = object_id('test') and autoval is null
ExpandedBlockEnd.gif
*/

None.gif
end
None.gif


2005-08-02 T-SQL Store Procedure 修订为:
完全不受字段数量或字段值影响 而生成正确完整的 INSERT INTO ... SQL

None.gif ALTER       procedure  Z_SP_GenInsertSQL
None.gif(
None.gif    
@tablename   varchar ( 256 )
None.gif    ,
@WhereClause      varchar ( 1000 =   ' where 1 = 1 '
None.gif)
None.gif
as
None.gif
begin
ExpandedBlockStart.gifContractedBlock.gif
/**/ /*
InBlock.gifusage:
InBlock.gifZ_SP_GenInsertSQL '表名','where dot.gif'
ExpandedBlockEnd.gif
*/

None.gif    
declare   @sql   varchar ( 8000 )
None.gif    
declare   @sqlValues   varchar ( 8000 )
None.gif    
set   @sql   = '   '' ( '''   +   char ( 13 +   ' , '
None.gif    
set   @sqlValues   =   '  values ( ''' +   char ( 13 +   ' , '
None.gif    
select   @sqlValues   =   @sqlValues   +  cols  +   '  +  '' , '   +   ''''   +   char ( 13 +   ' , '
None.gif            ,
@sql   =   @sql   +   ''' [ '   +  name  +   ' ], '''   +   char ( 13 +   ' , '
None.gif    
from
None.gif    (
None.gif        
select
None.gif            
case
None.gif                
when  xtype  in  ( 48 , 52 , 56 , 59 , 60 , 62 , 104 , 106 , 108 , 122 , 127 )
None.gif                    
then   ' case when  ' +  name  +   '  is null then  '' NULL ''  else  '   +   ' cast( '   +  name  +   '  as varchar) '   +   '  end '
None.gif                
when  xtype  in  ( 58 , 61 )
None.gif                    
then   ' case when  ' +  name  +   '  is null then  '' NULL ''  else  '   +   '''''''''  +  '   +   ' cast( '   +  name  +   '  as varchar) '   +   ' + '''''''''   +   '  end '
None.gif                
when  xtype  in  ( 167 , 175 )
None.gif                    
then   ' case when  ' +  name  +   '  is null then  '' NULL ''  else  '   +   '''''''''  +  '   +   ' replace( '   +  name  +   ' , '''''''' , '''''''''''' ) '   +   '  +  '''''''''   +   '  end '
None.gif                
when  xtype  in  ( 231 , 239 )
None.gif                    
then   ' case when  ' +  name  +   '  is null then  '' NULL ''  else  '   +   ''' N ''''''  +  '   +   ' replace( '   +  name  +   ' , '''''''' , '''''''''''' ) '   +   '  +  '''''''''   +   '  end '
None.gif                
else   ''' NULL '''
None.gif            
end   as  Cols
None.gif            ,name
None.gif        
from  syscolumns
None.gif        
where  id  =   object_id ( @tablename )
None.gif                
-- and autoval is null --忽略自增整型字段
None.gif
    ) T
None.gif    
set   @sql   =   ' select  '   +   char ( 13 +   ''' INSERT INTO  ''' +   char ( 13 +   ' , '
None.gif                 
+   ''' [ ' +   @tablename   +   ' ] '''   +   char ( 13 +   ' , '
None.gif                 
+   left ( @sql , len ( @sql ) - 4 +   ''''   +   char ( 13 +   ' , '' ) '   +   left ( @sqlValues , len ( @sqlValues ) - 7 +   ' , '' ) '''
None.gif                 
+   char ( 13 +   ' from [ '   +   @tablename   +   ' ] '
None.gif                 
+   char ( 13 +   @WhereClause
None.gif    
-- select @sql -- select SQL 被截断
None.gif
     print   @sql   --  print SQL 是完整正确的
None.gif
     exec  ( @sql )
ExpandedBlockStart.gifContractedBlock.gif
/**/ /*
InBlock.gifselect *
InBlock.giffrom syscolumns    
InBlock.gifwhere id = object_id('test') and autoval is null
ExpandedBlockEnd.gif
*/

None.gif
end
None.gif


 

转载于:https://www.cnblogs.com/Microshaoft/archive/2005/07/19/195752.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值