我尝试通过游标获取数据,例如下面的代码,但得到错误:
名为' MY_CURSOR'的光标已经存在。
我搜索并发现我应该在游标定义中使用LOCAL
字,例如DECLARE MY_CURSOR LOCAL CURSOR
,但会再次出错
DECLARE CURSOR语句中本地选项的使用无效。
我该如何解决这个问题?
DECLARE @tag AS NVARCHAR(1000)
DECLARE @tempTbl AS TABLE (tagcol NVARCHAR(1000))
DECLARE MY_CURSOR LOCAL CURSOR
FOR
SELECT bt.Tag
FROM BlogTable AS bt
WHERE bt.IsEnglish = 0
AND bt.IsActive = 1
AND bt.IsDelete = 0
OPEN MY_CURSOR
FETCH NEXT FROM MY_CURSOR INTO @tag
WHILE @@FETCH_STATUS = 0
BEGIN
INSERT INTO @tempTbl
SELECT *
FROM dbo.FunSpliteStr(@tag, '،')
FETCH NEXT FROM MY_CURSOR INTO @tag
END
CLOSE MY_CURSOR
DEALLOCATE MY_CURSOR
SELECT tagcol
FROM @tempTbl AS tt
GROUP BY
tt.tagcol
答案 0 :(得分:2)
非游标查询
SELECT *
FROM BlogTable AS bt
CROSS APPLY dbo.FunSpliteStr(bt.Tag, '،')
WHERE bt.IsEnglish = 0
AND bt.IsActive = 1
AND bt.IsDelete = 0
答案 1 :(得分:2)
我同意上面Larnu的评论。我将删除上面的光标并改为使用交叉应用。请看一下。
SELECT
bt.Tag,
*
FROM BlogTable AS bt
CROSS APPLY dbo.FunSpliteStr(bt.Tag, '،') FS
WHERE bt.IsEnglish = 0
AND bt.IsActive = 1
AND bt.IsDelete = 0
如果您仍然觉得“需要”游标,请先尝试单独运行close和deallocate语句,然后再次尝试运行while查询。
答案 2 :(得分:2)
尝试这个:这也是一种做法
DECLARE @tag AS NVARCHAR(MAX)
SELECT @tag = COALESCE(@tag + ',', '') + bt.Tag
FROM BlogTable AS bt
WHERE bt.IsEnglish = 0
AND bt.IsActive = 1
AND bt.IsDelete = 0
SELECT *
FROM dbo.FunSpliteStr(@tag, '،')
答案 3 :(得分:1)
虽然每个人都说你不需要光标(因此你不应该使用它),但回答你的实际问题:你应该在{{1}之后指定LOCAL | GLOBAL } keyword:
CURSOR