从包含游标的存储过程返回值

问题描述 投票:0回答:2

我有以下存储过程,我可以让它打印我需要的值/信息,但我希望能够返回值并使用它们填充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

任何帮助将非常感激。

sql-server tsql stored-procedures
2个回答
2
投票

我会避免使用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]

0
投票

您可以将数据添加到临时表并从那里进行选择

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
© www.soinside.com 2019 - 2024. All rights reserved.