Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 328
  • Last Modified:

SQL Concat Variable Cast at Runtime Returns NULL?

I'm trying to build a string of converted decimals into variable @Prices and keep getting null returns when I call this code in a separate query window:

   Declare @Prices      varchar(max) = NULL
   exec sp_MyTableTest @Prices OUTPUT
   select @Prices

   ---- Return ------
    NULL

ALTER PROCEDURE [dbo].[SP_MyTableTest]
(
	@Prices	 varchar(max) OUT
)

AS

BEGIN

Declare @Price		varchar(10)
Set @Prices = ''

Set @MyCursor = Cursor For Select Code, Name, Cast(Price as varchar(10) ) 
                                                  from tbl_Products 
        Open @MyCursor

	Fetch Next From @MyCursor
        Into @Price	

	While @@FETCH_STATUS = 0

		Begin
 
                        Set @Prices = @Prices + '''' + @Price + ''',' // Always returns Null

                        Set @Prices = ''''+ @Price + ''',' //WORKS!

                	Fetch Next From @MyCursor
                        Into @Name	
                End	

        Close @MyCursor
        Deallocate @MyCursor

Open in new window

0
WorknHardr
Asked:
WorknHardr
  • 2
2 Solutions
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
this should work better:
ALTER PROCEDURE [dbo].[SP_MyTableTest]
(
	@Prices	 varchar(max) OUT
)

AS

BEGIN

Declare @Price		varchar(10)
Set @Prices = ''

Set @MyCursor = Cursor For 
Select Cast(Price as varchar(10) ) as price 
 from tbl_Products 
  where price is not null

        Open @MyCursor

	Fetch Next From @MyCursor
        Into @Price	

	While @@FETCH_STATUS = 0

		Begin
 
                        Set @Prices = isnull(@Prices,'') + '"' + @Price + '",'

                	Fetch Next From @MyCursor
                        Into @price	
                End	

        Close @MyCursor
        Deallocate @MyCursor
                                  

Open in new window

0
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
you could shorten the code also, and avoid the cursor altogether:
ALTER PROCEDURE [dbo].[SP_MyTableTest]
(
	@Prices	 varchar(max) OUT
)

AS

BEGIN

Select @Prices = isnull(@prices, '') + '"' + Cast(Price as varchar(10) ) + '",'  
 from tbl_Products 
  where price is not null

END

Open in new window

0
 
WorknHardrAuthor Commented:
Excellent`a... thx
0

Featured Post

Fill in the form and get your FREE NFR key NOW!

Veeam is happy to provide a FREE NFR server license to certified engineers, trainers, and bloggers.  It allows for the non‑production use of Veeam Agent for Microsoft Windows. This license is valid for five workstations and two servers.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now