从包含游标的存储过程返回值
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从包含游标的存储过程返回值相关的知识,希望对你有一定的参考价值。
我有以下存储过程,我可以让它打印我需要的值/信息,但我希望能够返回值并使用它们填充C#应用程序中的下拉列表。
这是存储过程:
ALTER PROCEDURE sp_IHubTypes
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
DECLARE @NewsTypeID AS NVARCHAR(100)
DECLARE @Description AS NVARCHAR(100)
DECLARE @NTCount AS NVARCHAR(100)
DECLARE NewsCURSOR CURSOR FOR
SELECT NewsTypeID, Description
FROM tblNewsType
WHERE PortalID = 3
AND Sector = 'GENERIC'
AND Enabled = 1
ORDER BY RowOrder ASC, Description ASC
OPEN NewsCURSOR
FETCH NEXT FROM NewsCURSOR
INTO @NewsTypeID,@Description
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @NTCount = Count(0)
FROM tblAsset
WHERE NewsTypeS LIKE '%,' + CAST(@NewsTypeID AS nvarchar(100)) + ',%'
IF @NTCount > 0
BEGIN
PRINT '(' + @NTCount + ')' + @Description
END
FETCH NEXT FROM NewsCURSOR INTO @NewsTypeID,@Description
END
CLOSE NewsCURSOR
DEALLOCATE NewsCURSOR
END
当我在SQL Server Management Studio中执行存储过程时,print语句返回以下内容:
5 - Canada
3 - China
2 - Germany
3 - India
2 - Netherlands
1 - Russia
2 - UK
任何帮助将非常感激。
答案
我会避免使用CURSOR并像这样做一些SET:
SELECT COUNT(*) AS ItemCount,
nt.[Description] AS Country
FROM tblNewsType AS nt, tblAsset AS a
WHERE a.NewsTypes LIKE '%,' + CAST(nt.NewsTypeID AS nvarchar(100)) + ',%'
GROUP BY nt.[Description]
另一答案
您可以将数据添加到临时表并从那里进行选择
CREATE TABLE #TEMPDATA(ID int,COUNTRY varchar(100))
BEGIN
IF @NTCount > 0
BEGIN
INSERT INTO #TEMPDATA(ID,OUNTRY)
VALUES(@NTCount ,@Description)
END
FETCH NEXT FROM NewsCURSOR INTO @NewsTypeID,@Description
END
然后光标
SELECT ID,COUNTRY FROM #TEMPDATA
以上是关于从包含游标的存储过程返回值的主要内容,如果未能解决你的问题,请参考以下文章
如何从 Oracle 过程返回填充了 NESTED RECORD 类型的游标