如何在存储过程sql server 2005中使用循环
我是SQL服务器中的新成员。 我的要求是我必须从c#中取得数千条记录作为XML文件,并从该文件取得临时表中的数据。 从表中我必须检查一个接一个的记录,如果它存在,则更新else插入。 所以我写了一个存储过程,但它给我以下错误
消息102,级别15,状态1,过程InsertIntoMyTable,第13行
'cast'附近语法不正确。
消息102,级别15,状态1,过程InsertIntoMyTable,第18行
'LOOP'附近的语法错误。
消息156,级别15,状态1,过程InsertIntoMyTable,行25
关键字'END'附近的语法错误。
存储过程:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE InsertIntoMyTable
@mytable xml
AS
BEGIN
SELECT
cast(colx.query('data(PointsliceId) ') as int) as PointSliceId,
cast(colx.query('data(Pt_timestamp) ') as datetime) as Point_timestamp
cast(colx.query('data(FloatValue) ') as float) as Float_Value
INTo #TMP FROM @mytable.nodes('DocumentElement/mytable') AS Tabx(Colx)
For IDX in (select * from TMP)
LOOP
if((select count(*) from PointValue_Float where PointSliceId=IDX.PointSliceId and Pt_timeStamp=IDX.Pt_timeStamp)>0 )
update PointValue_Float set FloatValue=t.FloatValue from #TMP t where t.PointSliceId=PointValue_Float.PointSliceId and t.Pt_timeStamp=PointValue_Float.Pt_timeStamp
else
insert into PointValue_Float(PointSliceId,Pt_timeStamp,FloatValue) SELECT PointSliceId,Pt_timeStamp,FloatValue FROM #TMP
END LOOP
END
GO
在SQL Server过程中创建手动循环始终是一个坏主意 - SQL Server以数据集操作 - 而且您的语句也应该设置为导向。
在你的情况下,我会做的是这样的:
所以你的代码会是这样的:
CREATE PROCEDURE InsertIntoMyTable @mytable xml
AS BEGIN
SELECT
colx.value('(PointsliceId)[1]', 'INT') AS PointSliceId,
colx.value('(Pt_timestamp)[1]', 'DATETIME') AS Point_timestamp
colx.value('(FloatValue)[1]', 'FLAOT') AS Float_Value
INTO #TMP
FROM @mytable.nodes('DocumentElement/mytable') AS Tabx(Colx)
-- udpate the existing rows
UPDATE dbo.PointValue_Float
SET FloatValue = t.FloatValue
FROM #TMP t
WHERE t.PointSliceId = PointValue_Float.PointSliceId
AND t.Pt_timeStamp = PointValue_Float.Pt_timeStamp
-- remove those from the #TMP table
DELETE FROM #TMP
WHERE EXISTS
(SELECT * FROM dbo.PointValue_Float
WHERE PointSliceId = #TMP.PointSliceId AND Pt_timeStamp = #TMP.Pt_timeStamp)
-- INSERT the remaining rows
INSERT INTO
dbo.PointValue_Float(PointSliceId, Pt_timeStamp, FloatValue)
SELECT
PointSliceId, Pt_timeStamp, FloatValue
FROM #TMP
END
上一篇: how to use for loop in stored procedure sql server 2005