有时候根据工作需要可能要生成INSERT INTO TB(ID,COL) VALUES (1,'ABC')这样的数据脚本语句。
前几天根据以前在网上曾经看过的一个相关的脚本重新整理了一个可以实现此功能的存储过程,欢迎大家试用,如有任何问题或者bug可以给我留言。
废话不多说 上代码
USE [test] GO /****** Object: StoredProcedure [dbo].[pr_OutputData] Script Date: 03/05/2015 15:41:47 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: <Echo丶> -- Create date: <2015-02-21> -- Description: <生成数据脚本> -- ============================================= ALTER PROCEDURE [dbo].[pr_OutputData] @TABLE VARCHAR(50), @TTYPE BIT = 0 --0:默认导出整张表数据 --1:如果想根据WHERE条件导出数据就传入1,将语句打印出来自己手动在语句后边拼上WHERE条件 AS BEGIN SET NOCOUNT ON; IF OBJECT_ID(@TABLE) IS NULL BEGIN PRINT @TABLE+'表不存在' RETURN END DECLARE @SQL1 VARCHAR(4000) DECLARE @TYPE INT DECLARE @COLUMN VARCHAR(2000) DECLARE @COLUMN_NAME VARCHAR(100) DECLARE @DATA VARCHAR(3000) SET @COLUMN = '' SET @COLUMN_NAME = '' SET @DATA = '' SET @SQL1 = '' DECLARE CUR CURSOR FOR SELECT NAME,USER_TYPE_ID FROM SYS.COLUMNS WHERE OBJECT_ID = OBJECT_ID(@TABLE) AND is_identity <> 1 --过滤掉自增列 OPEN CUR FETCH NEXT FROM CUR INTO @COLUMN_NAME,@TYPE WHILE @@FETCH_STATUS=0 BEGIN SET @COLUMN = @COLUMN+CASE WHEN LEN(@COLUMN)=0 THEN '' ELSE ','END + @COLUMN_NAME SET @DATA = @DATA +CASE WHEN LEN(@DATA)=0 THEN '' ELSE ','','','END + CASE WHEN @TYPE IN(167,175) THEN '''''''''+'+@COLUMN_NAME+'+''''''''' --VARCHAR,CHAR WHEN @TYPE IN(35,241) THEN '''''''''+CAST('+@COLUMN_NAME+' AS VARCHAR(MAX))+''''''''' --TEXT,XML WHEN @TYPE IN(231,239) THEN '''N''''''+'+@COLUMN_NAME+'+''''''''' --NVARCHAR,NCHAR WHEN @TYPE=61 THEN '''''''''+CONVERT(VARCHAR(23),'+@COLUMN_NAME+',121)+''''''''' --DATETIME WHEN @TYPE=58 THEN '''''''''+CONVERT(VARCHAR(16),'+@COLUMN_NAME+',120)+''''''''' --SMALLDATETIME WHEN @TYPE=36 THEN '''''''''+CONVERT(VARCHAR(36),'+@COLUMN_NAME+')+''''''''' --UNIQUEIDENTIFIER ELSE @COLUMN_NAME END FETCH NEXT FROM CUR INTO @COLUMN_NAME,@TYPE END CLOSE CUR DEALLOCATE CUR --PRINT @COLUMN --PRINT @DATA SET @SQL1=' SELECT ''INSERT INTO '+@TABLE+'('+@COLUMN+') VALUES(''AS ''COL'','+@DATA+','')'' FROM '+@TABLE IF(@TTYPE = 0) BEGIN EXEC (@SQL1) END ELSE BEGIN PRINT @SQL1 END END
这是过年时候写的,比较简单,只做了将自增键过滤掉和增加where条件筛选功能。以后会根据需求修改的话,我会随时传最新版的上来。