2015年11月17日 星期二

for MSSQL2012 由查詢的結果產出insert 語法

「由查詢的結果產出insert 語法」(就某單一table查詢而言)
在toad 這樣的工具早就有這功能了,
在MSSQL 2008也有,叫 sp_generate_inserts
example:
EXEC sp_generate_inserts 'titles', @From = "from titles where title like '%Computer%'"
但是在MSSQL 2012 SQL 居然沒這麼好用的工具
放心,
這行就是這樣--很多事已經有人替你踢過鐵板了,你需要的,別人也有需要
以下就是這個產生insert語法的stored procedure:
===================================================================
/*
Authore : neeraj prasad sharma (please dont remove this :))
Example (1) Exec [dbo].[INS]  'Dbo.test where 1=1'
        (2) Exec [dbo].[INS]  'Dbo.test where name =''neeraj''' * for string

here Dbo is schema and test is tablename and 1=1 is condition

*/


CREATE procedure  [dbo].[INS]                              
(                                                          
   @Query  Varchar(MAX)                                                          
)                              

AS                              

       Set nocount ON                  

DEclare @WithStrINdex as INT                            
DEclare @WhereStrINdex as INT                            
DEclare @INDExtouse as INT                            

Declare @SchemaAndTAble VArchar(270)                            
Declare @Schema_name  varchar(30)                            
Declare @Table_name  varchar(240)                            
declare @Condition  Varchar(MAX)                             

SET @WithStrINdex=0                            

SELECT @WithStrINdex=CHARINDEX('With',@Query )                            
, @WhereStrINdex=CHARINDEX('WHERE', @Query)                            

IF(@WithStrINdex!=0)                            
Select @INDExtouse=@WithStrINdex                            
ELSE                            
Select @INDExtouse=@WhereStrINdex                            

Select @SchemaAndTAble=Left (@Query,@INDExtouse-1)                                                     
select @SchemaAndTAble=Ltrim (Rtrim( @SchemaAndTAble))                            

Select @Schema_name= Left (@SchemaAndTAble, CharIndex('.',@SchemaAndTAble )-1)                            
,      @Table_name = SUBSTRING(  @SchemaAndTAble , CharIndex('.',@SchemaAndTAble )+1,LEN(@SchemaAndTAble) )                            

,      @CONDITION=SUBSTRING(@Query,@WhereStrINdex+6,LEN(@Query))--27+6                            


Declare   @COLUMNS  table (Row_number SmallINT , Column_Name VArchar(Max) )                              
Declare @CONDITIONS as varchar(MAX)                              
Declare @Total_Rows as SmallINT                              
Declare @Counter as SmallINT              

declare @ComaCol as varchar(max)            
select @ComaCol=''                   

Set @Counter=1                              
set @CONDITIONS=''                              

INsert INTO @COLUMNS                              
Select  Row_number()Over (Order by ORDINAL_POSITION ) [Count] ,Column_Name FRom INformation_schema.columns Where Table_schema=@Schema_name                              
And table_name=@Table_name         


select @Total_Rows= Count(1) FRom  @COLUMNS                              

             Select @Table_name= '['+@Table_name+']'                      

             Select @Schema_name='['+@Schema_name+']'                      

While (@Counter<=@Total_Rows )                              
begin                               
--PRINT @Counter                              

    select @ComaCol= @ComaCol+'['+Column_Name+'],'            
    FROM @COLUMNS                              
Where [Row_number]=@Counter                          

select @CONDITIONS=@CONDITIONS+ ' +Case When ['+Column_Name+'] is null then ''Null'' Else ''''''''+                              

 Replace( Convert(varchar(Max),['+Column_Name+']  ) ,'''''''',''''  )                              

  +'''''''' end+'+''','''                              

FROM @COLUMNS                              
Where [Row_number]=@Counter                              

SET @Counter=@Counter+1                              

End                              

select @CONDITIONS=Right(@CONDITIONS,LEN(@CONDITIONS)-2)                              

select @CONDITIONS=LEFT(@CONDITIONS,LEN(@CONDITIONS)-4)              
select @ComaCol= substring (@ComaCol,0,  len(@ComaCol) )                            

select @CONDITIONS= '''INSERT INTO '+@Schema_name+'.'+@Table_name+ '('+@ComaCol+')' +' Values( '+'''' + '+'+@CONDITIONS                              

select @CONDITIONS=@CONDITIONS+'+'+ ''')'''                              

Select @CONDITIONS= 'Select  '+@CONDITIONS +'FRom  ' +@Schema_name+'.'+@Table_name+' With(NOLOCK) ' + ' Where '+@Condition                              
print(@CONDITIONS)                              
Exec(@CONDITIONS)  
=============================================================
出處在此
以上,大家加油吧



1 則留言:

  1. 補完一下:
    如果上述的script有問題的話,最直接的方式是另create一個table, 用select into 產生後,再用SQL Server Manager的task->generate script方式產生script,是最沒問題的了

    回覆刪除