此主题相关图片如下:表结构.jpg
如上图,现有一张表保存了每咱表单的名称及DataID号,根据DataID可以查到此单后台的所有数据,
而表B是记录每张表的单据编号列,现在为了得到表A中的单据编号是将表B存入游标再遍历与表A实现,方法如下:
IF OBJECT_ID('tempdb..#temp1') IS NOT NULL
DROP TABLE #temp1;
--数据存入临时表
SELECT a.*
INTO #temp1
FROM ( SELECT * ,
CAST(NULL AS NVARCHAR(16)) AS 单据编号
FROM dbo.表A
) a;
--更新各表及单据编号列更新实际的单据编号
DECLARE my_cursor CURSOR SCROLL
FOR
SELECT tbN ,
IDC
FROM dbo.表B
WHERE wintbN = winMtbN;
OPEN my_cursor;
DECLARE @tbn NVARCHAR(16);
DECLARE @idc NVARCHAR(16);
FETCH NEXT FROM my_cursor
INTO @tbn, @idc;
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE @sql NVARCHAR(MAX);
SET @sql = 'UPDATE a SET a.单据编号 = b.' + @idc
+ ' FROM #temp1 a left join
' + @tbn + ' b ON a.DataID = b.DataID where a.单据名称 = '''
+ @tbn + '''';
EXEC sp_executesql @sql;
FETCH NEXT FROM my_cursor
INTO @tbn,@idc
END;
CLOSE my_cursor;
DEALLOCATE my_cursor
SELECT * FROM #temp1
有没有直接查询的方法实现?
谢谢!