sql fetch提取数据常用方法

如题所述

1、查询数据库(test)中的所有表名的方法:

SELECT name
FROM [test]..sysobjects where xtype='U'
********
补充:
如果有的表不存在【时间】那就用下面的语句直接把含有【时间】列的表名找到:
SELECT d.name
FROM [test]..syscolumns a
inner join [test]..sysobjects d on a.id=d.id and d.xtype='U' and a.name='时间'
**********

2、遍历这个表名取出数据插入到另外的数据库中(SqlServer中的遍历方法我不是很清楚,给你提供个思路,oracle的话我就能把程序写出来了O(∩_∩)O~)。

如:遍历结果存储到数据库test2中
insert into [test2]..遍历出的表名 select * from 遍历出的表名 where datediff(day,'2009-08-07',时间)>0;

重复上面的sql语句指导讲数据库test中的表名完全遍历完为止。

*************************************************************
补充:我试验了一下下面把实验代码给你(建一个存储过程)
create proc test as
--定义游标变量
declare cur1 cursor for
SELECT d.name
FROM [test]..syscolumns a
inner join [test]..sysobjects d on a.id=d.id and d.xtype='U' and a.name='时间'
--定义临时变量
declare @tmp varchar(1000)
--定义sql字符串
declare @strsql varchar(4000)
--打开游标
open cur1
--读取第一条数据,也就是第一个表名
fetch next from cur1 into @tmp
--是读完
while(@@fetch_status = 0)
begin
--连接sql文
set @strsql='insert into [test2]..'+@tmp++' select * from '+@tmp+' where datediff(day,'+char(39)+'2009-08-07'+char(39)+',时间)>0'
--执行这个sql
exec(@strsql)
--读取下一条数据
fetch next from cur1 into @tmp
end
--关闭游标
close cur1
--摧毁游标所占资源
deallocate cur1
温馨提示:答案为网友推荐,仅供参考
第1个回答  2018-11-08
HSTMT stmt;
char * sqlquery="select branch_name,sum(balance) from account group by branch_name";
SQLAllocStmt(conn,&stmt);
error=SQLExecDirect(stmt,(SQLCHAR*)sqlquery,SQL_NTS);
if (error==SQL_SUCCESS)
{
SQLBindCol(stmt,1,SQL_C_CHAR,branchname,80,&lenOut1);

SQLBindCol(stmt,2,SQL_C_FLOAT,&balance,0,&lenOut2);
error=SQLFetch(stmt);
SQLGetDiagRec(SQL_HANDLE_STMT,stmt,RecNumber,SQLState, NativeErrorPtr,MessageText, BufferLength,TextLengthPtr);
cout<<SQLState<<":"<<MessageText<<endl;
while (SQLFetch(stmt)==SQL_SUCCESS){
printf("%s%g\n",branchname,balance);
}
}
相似回答