View Single Post

   
  #3 (permalink)  
Old 02-29-2008, 08:30 AM
Highlander416
 
Posts: n/a
Default Re: sp_ExecuteSQL in User Defined Function

Hey Erland,

I will describe the business problem I'm trying to solve, but first let
me mention there is another alternative to finding yourself trying to
do such a thing: a problem is being over-complicated. I ended up using
a Stored Procedure that incorporated both items in code. It's not
perfect (in fact - a little clunky), but it did solve the problem.

I am generating a form (intended for print) that will be populated with
information from a web app (should it exist). This form is meant for
developers to use to interview various businesses within an
organization to determine what systems (software) they are currently
using. The intent is to capture information about these systems and
then to use that for planning purposes, strategic alignment, etc.
Since I'm taking a web based form (several screens and what not) and
turning it into a form intended for print, I had to overcome certain
challenges: particularly those involving drop-down lists that must now
become groups of check-boxes. This is why I needed the bit field - to
pre-populate the necessary check boxes.

So here's the solutions I ended up with:

CREATE PROCEDURE dbo.SelectedByApplication
(
@FromTable NVarChar(50) = 'IPM_DataType',
@ValueColumnToCompare NVarChar(50) = 'DataTypeID',
@TableToCheck NVarChar(50) = 'IPM_Application_DataType',
@ColumnToCompare NVarChar(50) = 'DataTypeID',
@ApplicationID INT = 4
)
AS

DECLARE @SQL NVarChar(1000)
DECLARE @Param NVarChar(500)

SET @SQL = N'SELECT *, (SELECT COUNT(*) FROM [' + @TableToCheck + ']
WHERE [' + @ColumnToCompare + '] = T.[' + @ValueColumnToCompare + ']
' +
'AND ApplicationID = @ApplicationID) AS Selected ' +
'FROM [' + @FromTable + '] AS T'
SET @Param = N'@ApplicationID INT'
EXEC sp_ExecuteSQL @SQL, @Param, @ApplicationID

As I said, it is a bit clunky - but it does perform the task I need.
Let me know if you have any suggestions for improvement.

Reply With Quote