我有以下查询,可将数据插入表中。问题是有很多记录,并且它填充了数据库中的事务日志。因此,我需要分批插入或使用游标。任何人都知道如何使用游标将以下查询重构为工作状态?
SELECT
h.issue_id,
h.account_id,
h.shares_held,
h.shares_change,
a.current_report_date
INTO #tmp_holding
FROM edgar_holding h
JOIN edgar_account a ON h.account_id = a.account_id
INSERT INTO edgar_holding_hist
SELECT
h.issue_id,
h.account_id,
h.shares_held,
h.shares_change,
h.current_report_date
FROM #tmp_holding h
LEFT JOIN edgar_holding_hist hh
ON hh.account_id = h.account_id
AND hh.issue_id = h.issue_id
AND hh.current_report_date = h.current_report_date
WHERE hh.issue_id IS NULL
OR hh.account_id IS NULL
OR hh.current_report_date IS NULL
DROP TABLE #tmp_holding
您可以通过几种不同的方式来执行此操作。一种是在初始查询中声明游标,另一种是在#temp表中声明游标。
为简单起见,我将使用#temp表:
DECLARE holding_cursor FOR
SELECT
h.issue_id,
h.account_id,
h.shares_held,
h.shares_change,
h.current_report_date
FROM #tmp_holding h
LEFT JOIN edgar_holding_hist hh
ON hh.account_id = h.account_id
AND hh.issue_id = h.issue_id
AND hh.current_report_date = h.current_report_date
WHERE hh.issue_id IS NULL
OR hh.account_id IS NULL
OR hh.current_reporting_data IS NULL
DECLARE
@issue_id [insert datatype here],
@account_id [insert datatype here],
@shares_held [insert datatype here],
@shares_change [insert datatype here],
@current_report_date [insert datatype here]
OPEN holding_cursor
fetch holding_cursor into @issue_id, @account_id, @shares_held, @shares_change, @current_report_date
WHILE (@@sqlstatus = 0)
BEGIN
INSERT INTO edgar_holding_hist (issue_id, account_id, shares_held, shares_change, current_report_date)
VALUES (@issue_id, @account_id, @shares_held, @shares_change, @current_report_date)
FETCH holding_cursor into @issue_id, @account_id, @shares_held, @shares_change, @current_report_date
END
CLOSE holding_cursor
DEALLOCATE holding_cursor
DROP TABLE #tmp_holding
类似的东西应该起作用。由于您还担心事务日志,因此可以经常使用if
语句使用@@rowcount
发出转储tran,该操作将自打开游标以来获取的行数作为计数器进行计数。
我想将特定创建者的所有表的选择权限授予用户。我正在使用以下过程。
create or replace procedure grantalltables
@CreatorName varchar(255),
@UserName varchar(255)
as
declare @sqlCommand varchar(1000)
declare @table_name varchar(55)
DECLARE curThisCust CURSOR FOR
select tname from SYS.SYSCATALOG where upper(creator)=upper(@CreatorName)
OPEN curThisCust ;
fetch next curThisCust into @table_name
WHILE (@@sqlstatus = 0)
BEGIN
SET @sqlCommand = 'grant select on '+ @table_name +' to ' + @UserName
EXECUTE (@sqlCommand)
fetch next curThisCust into @table_name
END
print 'Grant Successfuly given'
close curThisCust
DEALLOCATE curThisCust
我使用相同的语法,但是在我的过程中,仅处理第一行。如果有人可以帮助。