我正在嘗試編寫一個程序來檢查表中的所有行,並且如果itemID = 'CC100'
那麼我需要在表中插入一個新行。我已經產生了這個腳本,但是當我嘗試執行它以編程方式將行插入表
消息156,級別15,狀態1,行中的關鍵字「選擇」 33
附近有語法錯誤,我得到一個錯誤。
這應該如何改變成爲有效的t-sql,或者什麼是更合適的方式來實現我想要的結果?樣品DDL低於:
--Create Holding Table
Declare Table #Items
(
itemID varchar(20)
,itemName varchar(100)
,qty int
,storeID int
)
--Insert Some Sample Data
Insert Into #Items (itemID, itemName, qty, storeID) Values
('CZ100', 'Coke Zero', 4, 123), ('CZ100', 'Coke Zero', 3, 201)
,('CZ200', 'Cherry Coke Zero', 4, 311), ('CC100', 'Coca-Cola', 6, 400)
,('CC100', 'Coca-COla', 8, 500)
--Select data that needs to be split into secondary table
Select storeID, Qty Into #NeedExtra from #Items WHERE itemID = 'CC100'
--Declare variables
Declare @storeID int, @Qty int
--Create Cursor
DECLARE cursor1 CURSOR FOR
--Select statement to insert into variables
SELECT
storeID, qty
FROM #NeedExtra
OPEN cursor1
--Iterate cursor
FETCH NEXT FROM cursor1 INTO @storeID, @qty
--Continue as long as cursor is not empty
WHILE @@FETCH_STATUS = 0
BEGIN
--Insert Values
Insert Into #Items (itemID, itemName, qty, storeID) Values
Select @storeID, 'CC200', 'Coca-Cola Syrup', @Qty, @storeID FROM #NeedExtra
--Grab next item from temp table
FETCH NEXT FROM cursor1 INTO @storeID, @qty
END
--Close cursor
CLOSE cursor1
--Deallocate cursor
DEALLOCATE cursor1
--Select statements
Select * FROM #NeedExtra
SELECT * FROM #Items
一個沒有光標的方法。我喜歡這個! – BellHopByDayAmetuerCoderByNigh