SQL SERVER将查询数据转为INSERT语句

2022-05-30 14:19:39 浏览数 (1)

1、在Sql Server数据库中创建存储过程

个人感觉挺有用,Mark一下。

代码语言:javascript复制
CREATE PROC sp_Data2InsertSQL
@TableName AS VARCHAR(100)
AS
 
DECLARE	xCursor CURSOR FOR
 
SELECT name,xusertype
FROM syscolumns
WHERE (id = OBJECT_ID(@TableName))
 
DECLARE @F1 VARCHAR(100)
DECLARE @F2 integer
DECLARE @SQL varchar(8000)
 
SET @sql ='SELECT ''INSERT INTO '   @TableName   ' VALUES('''
 
OPEN xCursor
FETCH xCursor INTO @F1,@F2
WHILE @@FETCH_STATUS = 0
 
BEGIN
SET @sql = @sql   ''
        CASE WHEN @F2 IN (35,58,99,167,175,231,239,61) then '   CASE WHEN '   
        @F1   ' IS NULL THEN '''' ELSE '''''''' END   ' ELSE ' ' END 
        'REPLACE(ISNULL(CAST('   @F1   ' AS VARCHAR(8000)),''NULL''),'''''''','''''''''''')'     
        CASE WHEN @F2 IN (35,58,99,167,175,231,239,61) THEN '   CASE WHEN '   
        @F1   ' IS NULL THEN '''' ELSE '''''''' END   ' ELSE ' ' END    
        CHAR(13)   ''','''
FETCH NEXT FROM xCursor INTO @F1,@F2
END
 
CLOSE xCursor
 
DEALLOCATE xCursor
 
SET @sql = LEFT(@sql,LEN(@sql) - 5)   '   '')'' FROM '   @TableName
 
EXEC (@sql)
 
GO

2、执行存储过程

代码语言:javascript复制
// 输入代码内容

EXEC sp_Data2InsertSQL YourTable

3、转发地址:

https://blog.csdn.net/wyx177694333/article/details/8211229?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_baidulandingword~default-0-8211229-blog-45166391.pc_relevant_scanpaymentv1&spm=1001.2101.3001.4242.1&utm_relevant_index=3

0 人点赞