我正在尝试在 SQL Server 2008 中创建一个将临时表中的数据插入到现有表中的过程。我想我已经弄清楚了,我只是遇到了循环问题。我需要临时表中的行数来确定循环何时结束。
我尝试以两种不同的方式使用@@ROWCOUNT;在 WHILE 语句中单独使用它,并创建一个变量以在第一个循环完成时尝试保存该值(参见下面的代码)。
这些方法都没有奏效,我现在不知道该怎么做。在这种情况下可以使用@@ROWCOUNT,还是有另一种更好的方法?
CREATE PROCEDURE InsertData(@KeywordList varchar(max))
AS
BEGIN
--create temp table to hold words and weights
CREATE TABLE #tempKeywords(ID int NOT NULL, keyword varchar(10) NOT NULL);
DECLARE @K varchar(10), @Num int, @ID int
SET @KeywordList= LTRIM(RTRIM(@KeywordList))+ ','
SET @Num = CHARINDEX(',', @KeywordList, 1)
SET @ID = 0
--Parse varchar and split IDs by comma into temp table
IF REPLACE(@KeywordList, ',', '') <> ''
BEGIN
WHILE @Num > 0
BEGIN
SET @K= LTRIM(RTRIM(LEFT(@KeywordList, @Num - 1)))
SET @ID = @ID + 1
IF @K <> ''
BEGIN
INSERT INTO #tempKeywords VALUES (@ID, @K)
END
SET @KeywordList = RIGHT(@KeywordList, LEN(@KeywordList) - @Num)
SET @Num = CHARINDEX(',', @KeywordList, 1)
--rowcount of temp table
SET @rowcount = @@ROWCOUNT
END
END
--declaring variables for loop
DECLARE @count INT
DECLARE @t_name varchar(30)
DECLARE @key varchar(30)
DECLARE @key_weight DECIMAL(18,2)
--setting count to start from first keyword
SET @count = 2
--setting the topic name as the first row in temp table
SET @t_name = (Select keyword from #tempKeywords where ID = 1)
--loop to insert data from temp table into Keyword table
WHILE(@count < @rowcount)
BEGIN
SET @key = (SELECT keyword FROM #tempKeywords where ID = @count)
SET @key_weight = (SELECT keyword FROM #tempKeywords where ID = @count+2)
INSERT INTO Keyword(Topic_Name,Keyword,K_Weight)
VALUES(@t_name,@key,@key_weight)
SET @count= @count +2
END
--End stored procedure
END