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

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

Select records from an MS SQL 2K table using value list parameter

I'm contructing a stored proc like the following:

CREATE PROCEDURE Select_Widgets
    @WidgetsList varChar(20)
    AS
    Select * From Table1
    Where WidgetID In(@WidgetsList )

but am getting the following error from sql server 2k when running through the debugger: 'Syntax error converting the varchar value '2,5' to a column of data type int'.  The target field is an int, so I'm passing a comma delimited list of int values without quotes around each value.
0
LloydMc
Asked:
LloydMc
1 Solution
 
jdlambert1Commented:
Don't know if there's a better way, but this works:

CREATE PROCEDURE Select_Widgets
    @WidgetsList varChar(20)
AS

DECLARE @sql nvarchar(888)

SET @sql = 'Select * From Table1 Where WidgetID In ( ' + @WidgetsList + ') '

EXEC sp_executesql @sql
0
 
QlemoC++ DeveloperCommented:
jdlambert1: I agree, this is 'the' solution, no better choices availlable ...
0
 
SjoerdVerweijCommented:
Ehm... how about

Create Procedure Select_Widgets
  @WidgetList VarChar(255)
As
Begin

  Declare @TWidget Table(ID Int)

  Declare @P Int

  While (@P > 0)
    Begin
      Set @P = CharIndex(',', @WidgetList)
      If (@P <= 0)
        Insert Into @TWidget(ID) Values(Cast(@WidgetList As Int))
      Else
        Begin
          Insert Into @TWidget(ID) Values(Cast(Left(@WidgetList, @P-1) As Int))
          Set @WidgetList = SubString(@WidgetList, @P + 1, 255)
        End
    End
 
  Select * From Table1 Where WidgetID In (Select ID From @TWidget)

End
Go

No dynamic SQL needed.
0
Learn Veeam advantages over legacy backup

Every day, more and more legacy backup customers switch to Veeam. Technologies designed for the client-server era cannot restore any IT service running in the hybrid cloud within seconds. Learn top Veeam advantages over legacy backup and get Veeam for the price of your renewal

 
arbertCommented:
Have to agree with SjoerdVerweij here.  Looks overly complicated, but you don't have the penalty of Dynamic SQL and you don't have to worry about the security implications of dynamic sql...
0
 
QlemoC++ DeveloperCommented:
If security is an issue, last solution is best. If it is not, first solution is more fexible, since you can use a subselect as argument (and this is indeed the security break ...).
0
 
SjoerdVerweijCommented:
Call the first version like so:

Select_Widgets '0);select user --'

It's called a SQL injection attack.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

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