SQL QUERY用于select查询中的insert语句

时间:2016-12-08 11:34:20

标签: sql postgresql

输出格式:

INSERT INTO Table (columns) VALUES (records of this table)

示例:

INSERT INTO Table1 (columns of Table1 ) VALUES (records of this table1)
INSERT INTO Table2 (columns of Table2) VALUES (records of this table2)
INSERT INTO Table3 (columns of Table3) VALUES (records of this table3)
INSERT INTO Table4 (columns of Table4) VALUES (records of this table4)
.
.
.
.
.
. etc....

注意:OUTPUT应该是这样的..它应该逐个显示数据库/模式中的所有表数据。我需要一个SQl查询这个要求???

2 个答案:

答案 0 :(得分:0)

试试这个:用表格替换tablename

Declare @table varchar(100)=<tablename>
Declare @count int,@query varchar(maX),@quer varchar(maX)
declare @col table(col varchar(100),id int identity(1,1))
insert into @col
select name from master.sys.columns 
where object_id=(select object_id from master.sys.tables where name=@table)


set @count=0
set @query='INSERT INTO '+@table+' ('
while @count<(select count(*) from @col)
begin
set @query=@query+(select col from @col where id=(@count+1))+','
set @count=@count+1
end

set @query=substring(@query,0,len(@query))+') values ('


set @count=0
set @quer='select '''+@query+'''''''+'
print @quer
while @count<(select count(*) from @col)
begin
set @quer=@quer+'cast('+(select col from @col where id=(@count+1))+' as varchar(maX))+'''''',''''''+'
set @count=@count+1
end
set @quer=substring(@quer,0,len(@quer)-6)+''''')'' from '+@table
exec (@quer)

答案 1 :(得分:0)

的PostgreSQL。

    create language plpythonu;
    create or replace function geninsert1(_table text)
    returns setof  text
    as
    $$
    def isstr(v):
        if v == None:
            return 'NULL'
        elif isinstance(v,str):
            return "'%s'" % v
        else:
            return str(v)

    alist=[]
    result = plpy.execute("select * from "+_table)
    for x in result:
        fieldlist=x.keys()
        fields=','.join(fieldlist)
        fvalues=','.join([isstr(x[y]) or 'NULL' for y in fieldlist])
        sql="insert into %s (%s) VALUES(%s)" % (_table,fields,fvalues)
        alist.append(sql)
    return alist
    return ''
    $$
    language plpythonu;
    select * from geninsert1('mutable');