【問題】DB結構的發布,SQL Server的管理器可以生成腳本;那麼數據如何發布呢?
【思路】生成INSERT INTO ... VALUES...語句
/*-- ============================================= -- Author: Yew -- Create date: 2012-05-18 -- Description: 生成數據發布的INSERT腳本 ----TestCode--------------------------- EXEC [TOOL].[Script_Insert] @Schema = 'COMMON' ,@Table = 'Config' ,@Filter = '[Key] LIKE ''test%'' ' ,@Field0 = '[Key]' ,@Field1 = 'SubKey' ,@Field2 = 'Value' ,@Field3 = null ,@Field4 = null EXEC [TOOL].[Script_Insert] @Schema = 'COMMON' ,@Table = 'MasterData' ,@Filter = 'Category = ''SheetItem_PreloadType'' ' ,@Field0 = 'Category' ,@Field1 = 'Code' ,@Field2 = 'Name' ,@Field3 = 'Ord' ,@Field4 = null ----History--------------------------- -- =============================================*/ ALTER PROCEDURE [TOOL].[Script_Insert] @Schema sysname = 'dbo' ,@Table sysname ,@Filter sysname = null ,@Field0 sysname ,@Field1 sysname = null ,@Field2 sysname = null ,@Field3 sysname = null ,@Field4 sysname = null AS BEGIN SET NOCOUNT ON; -- 0. Define Const DECLARE @NL varchar(2) --NewLine SET @NL = char(13) + char(10) DECLARE @vSql NVARCHAR(max) ,@objName sysname ,@fieldList sysname -- 1. prepare the statement IF @Schema = '' SET @Schema = 'dbo' SET @objName = @Schema + '.' + @Table SET @vSql = 'SET QUOTED_IDENTIFIER OFF; SELECT "INSERT INTO ' + @objName + '(' + @Field0 IF @Field1 IS NOT NULL SET @vSql = @vSql + ' ,' + @Field1 IF @Field2 IS NOT NULL SET @vSql = @vSql + ' ,' + @Field2 IF @Field3 IS NOT NULL SET @vSql = @vSql + ' ,' + @Field3 IF @Field4 IS NOT NULL SET @vSql = @vSql + ' ,' + @Field4 SET @vSql = @vSql + ' )' + @NL + 'VALUES(" + QuoteName(' + @Field0 + ', Char(39))' IF @Field1 IS NOT NULL SET @vSql = @vSql + @NL + ' +", " + QuoteName(IsNull(' + @Field1 + ', ""), Char(39))' IF @Field2 IS NOT NULL SET @vSql = @vSql + @NL + ' +", " + QuoteName(IsNull(' + @Field2 + ', ""), Char(39))' IF @Field3 IS NOT NULL SET @vSql = @vSql + @NL + ' +", " + QuoteName(IsNull(' + @Field3 + ', ""), Char(39))' IF @Field4 IS NOT NULL SET @vSql = @vSql + @NL + ' +", " + QuoteName(IsNull(' + @Field4 + ', ""), Char(39))' SET @vSql = @vSql + @NL + ' +")"' + @NL + 'FROM ' + @objName IF @Filter IS NOT NULL SET @vSql = @vSql + @NL + 'WHERE ' + @Filter -- 2.run it PRINT @vSql EXEC(@vSql) END
【注1】原本一個小工具,也不過花了2個小時,並不值得寫篇Blog。但一來,這個工具很多人需要;二來這是今天重感冒下做出來的(當我這篇blog寫到一半時,感冒消失了),更顯珍貴。
【注2】對於這個‘分享’:
想做:但是我發現新人們大多不太注重編碼規范、牛人們不願意平衡功能與成本,這段代碼裡面很有些參照價值;
可做:這是個純粹的工具,不涉及機密;
能做:這個工具足夠小,很容易說清楚、看明白。
還請讀者們對作品本身發表意見。
本文出自 “葉偉(魔教教主)” 博客,請務必保留此出處http://davyyew.blog.51cto.com/1084625/868414