Monday, 9 September 2013

Stored Procedure to query data using list parameter

Working on this task required me to create a stored procedure which will get a list of strings, do some processing on them and then return some data. Since SQL Server 2000 don't support arrays object so I had to find a different approach. After a bit of googling i figured out I can send list by building a string out of it and then in SQL Server use function "IN" to do processing as required.

Here'e the Stored Procedure,

USE [DataBaseName]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


Create PROCEDURE [dbo].[StoredProcedureName]
(
@listParameter varchar(8000)   -- this is because SQL Server don't support "Max" --
)
AS

exec('SELECT  *
FROM TableName
WHERE ColumnaName IN (' +@PasswordPolicyGroups+ ')   -- checks for list of values --
and CoumnaNameB= 1')

Now I am providing list as

List<String> myListData = GetListData(); // or your logic
string tempListData = string.Empty;

foreach(string data in myListData)
     data += "'" + myListData + "',";

// now just pass data as your parameter and call stored procedure


No comments:

Post a Comment