0

I have the following stored procedure and I can get it to print the values/information that I require, but I would like to be able to return the values and use them to populate a dropdownlist in a C# application.

This is the stored procedure:

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

When I execute the stored procedure in SQL Server Management Studio the print statement returns the following:

 5 - Canada
 3 - China
 2 - Germany
 3 - India
 2 - Netherlands
 1 - Russia
 2 - UK

Any help would be much appreciated.

4

2 回答 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]
于 2013-09-13T17:04:56.070 回答
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
于 2013-09-13T15:55:32.853 回答