【问题】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】对于这个‘分享’:
- 想做:但是我发现新人们大多不太注重编码规范、牛人们不愿意平衡功能与成本,这段代码里面很有些参照价值;
- 可做:这是个纯粹的工具,不涉及机密;
- 能做:这个工具足够小,很容易说清楚、看明白。
还请读者们对作品本身发表意见。
本文转自DavyYew 51CTO博客,原文链接:http://blog.51cto.com/davyyew/868414 ,如需转载请自行联系原作者