Re: (SQL) Using Variable in select command



Robert wrote on Tue, 2 May 2006 07:35:03 -0700:

I am trying to use the following select statement in the stored procedure

Select * from mytable where PIN in (@MyPINS)

PIN is varchar(5) and @MyPINS is varchar(50) that i get it as input to the
stored procedure.
when i give the input to @MyPINS like 1,2,3 i get no answer but if i write
the query like
Select * from mytable where PIN in (1,2,3)
i get some output. i think i know what is the problem. the problem is that
the query get the @MyPINS as '1,2,3' and the query will be like
Select * from mytable where PIN in ('1,2,3')
but i don't know how to solve the proble.
please help me.

Thanks

You can't use a variable like that. You will need to construct "dynamic
sql", eg.

/*create a variable, this can be replaced with a parameter later */
/* if PIN is varchar(5), make @MyPINS big enough to hold as many possible
PIN values, change the 10 as needed */
Declare @MyPINS varchar(10)
Set @MyPINS = '1,2,3'

/*add quotes to the variable as required */
Set @MyPINS = '''' + REPLACE(@MyPINS, ',' , ''',''') + ''''

/* execute the dynamic sql */
exec 'SELECT * FROM MyTable WHERE PIN IN (' + @MyPINS + ')'


The above might not run - I typed it from memory while taking a teabreak, so
I might have missed something.

Dan


.



Relevant Pages

  • Re: Two Questions on Forms for Access Database Project
    ... To set a control in a form equal to a control in another form: ... create a query and use the Unmatched Query ... Or simply create a query and add the main table (PIN #) and the ... I just picked up a project building an Access Database for a real estate ...
    (microsoft.public.access.formscoding)
  • Re: List Box Display Anomaly
    ... You undoubtedly saved me several hours trying to pin this one down. ... There were some bugs introduced by SP3 for Office 2003, including combo display problems: ... The underlying query uses two tables. ... I delivered a new front-end to a client this morning and he alerted me the anomaly. ...
    (microsoft.public.access.forms)
  • Query on Queries
    ... I generated a SQL query using Wizard and got the following ... I wanted to add another condition to my Query and also modify the ... Just to give a background the "Prod Mfg SKU ... Cd" would be a subset of PIN. ...
    (microsoft.public.access.queries)
  • Re: SQL syntax to update records with diffrent function generated random PINS
    ... >> The following sql query updates records with the SAME PIN number but. ... In ASP I looped through the set assigning new values and then OUTSIDE ... the loop I updated the set rs1.UPDATE. ...
    (comp.lang.php)
  • Re: SQL syntax to update records with diffrent function generated random PINS
    ... >> The following sql query updates records with the SAME PIN number but. ... In ASP I looped through the set assigning new values and then OUTSIDE ... the loop I updated the set rs1.UPDATE. ...
    (comp.lang.php)