SQLUSA

Microsoft SQL Server 2000 Best Practices

 

How to find customers by region with dynamic SQL?

 

The following dynamic SQL stored proc can be used by a VB or ASP.NET application to return a dynamic result set based on user entry:

USE Northwind

CREATE PROCEDURE CustomerListByState @States varchar(100)
AS
BEGIN
declare @sql varchar(8000)
set @sql = 'select CustomerID, CompanyName, ContactName, Phone, Region
from Customers where Region IN (' + @States + ')' + 'order by Region'
--print @sql
execute (@sql)
END
GO

-- execute script
declare @States varchar(100)
set @States = '''WA'', ''OR'', ''ID'', ''CA'''
exec CustomerListByState @States
GO

American Standard in SQL Server Training
 
SQLUSA.com Home Page