473,509 Members | 3,075 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

sp_ExecuteSQL in User Defined Function

This is driving me crazy.

I need to create a UDF that would return a TRUE/FALSE (bit) value based
on a comparison it does.

CREATE FUNCTION dbo.SelectedByApplication
(
@ApplicationID int,
@TableToCheck nvarchar(50),
@ColumnToCompare nvarchar(50),
@ValueInTable int
)
RETURNS BIT AS
BEGIN

DECLARE @SQL NVARCHAR(1000)
DECLARE @Param NVARCHAR(500)
DECLARE @Result int
SET @SQL = N'SELECT @result = COUNT(*) FROM [' + @TableToCheck + '] '
+
'WHERE [' + @ColumnToCompare + '] = @ValueInTable AND
ApplicationID = @ApplicationID'
SET @Param = N'@result int out, @ValueInTable int, @ApplicationID
int'
EXECUTE sp_executesql @SQL, @Param, @result out, @ValueInTable,
@ApplicationID

if @result > 0
return 1
return 0
END

All I need the function to do is fill in a column based on whether
there is a relation between a list of data and the item. I'm trying to
use it in the following query:

SELECT *, EXEC dbo.SelectedByApplication(4, 'IPM_Application_DataType',
'DataTypeID', DataTypeID)
FROM IPM_DataType DT

The idea is to make this call and then be able to populate a list of
checkboxes based on the information it returns. It should return
something similiar to:

Column1 Column2 UDFColumn
1 SomeValue 0
2 OtherValue 1
3 DifferentValue 0
4 LastValue 1

After reading some of the posts and discovering you can't execute
dynamic SQL in a UDF I decided to split the function into a function
and stored procedure:

CREATE FUNCTION dbo.SelectedByApplication
(
@ApplicationID int,
@TableToCheck nvarchar(50),
@ColumnToCompare nvarchar(50),
@ValueInTable int
)
RETURNS BIT AS
BEGIN

Declare @Result INT

EXEC DynamicCompare @ApplicationID, @TableToCheck, @ColumnToCompare,
@ValueInTable, @Result

if(@Result > 0)
return 1
return 0
END

CREATE PROCEDURE dbo.DynamicCompare
(
@ApplicationID int,
@TableToCheck nvarchar(50),
@ColumnToCompare nvarchar(50),
@ValueInTable int,
@Result int out
)
AS
DECLARE @SQL NVARCHAR(1000)
DECLARE @Param NVARCHAR(500)

SET @SQL = N'SELECT @result = COUNT(*) FROM [' + @TableToCheck + ']
' +
'WHERE [' + @ColumnToCompare + '] = @ValueInTable AND
ApplicationID = @ApplicationID'
SET @Param = N'@result int out, @ValueInTable int, @ApplicationID
int'

EXECUTE sp_executesql @SQL, @Param, @result out, @ValueInTable,
@ApplicationID

I get the same error message about only being able to execute functions
and extended stored procedures in a user defined function.

Does anyone have any ideas as to how I can dynamically execute this
query? The reason I say dynamic is I need this same comparison for
about 25 different tables. Thanks!

Jul 23 '05 #1
2 11890
Highlander416 (rb*******@gmail.com) writes:
Does anyone have any ideas as to how I can dynamically execute this
query? The reason I say dynamic is I need this same comparison for
about 25 different tables. Thanks!


You cannot invoke dynamic SQL from a user-defined function.

I don't really get a grip of what you are trying to do. Even less why.
And that would be kind of interesting to know.

Because, normally, if find yourself wanting to do such a thing, it's
a strong indication that there is a problem with the data model. Then
again, it could be OK, if this is for some special purpose, for instance
auditing or reconciliation, and part of the main application code.

If you can expand on the underlyingh business problem you have, it may
be easier to suggest a strategy.

--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 23 '05 #2
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.

Jul 23 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
4847
by: cliverama | last post by:
help! fried brains.... asp calling a sqlserver7 stored proc which dynamically builds a sqlstatement & passes it to sp_executesql asp page gives the operation not allowed when object is closed...
1
38564
by: Justin Wong | last post by:
CREATE PROCEDURE dbo.Synchronization_GetNewRecords ( @item varchar(50), @last datetime ) AS SET NOCOUNT ON
3
40996
by: Clausmeyer | last post by:
I want to execute a dynamically generated sql-statement from inside an user-defined-function. Calling functions and extended stored-procs is allowed so I tried sp_executesql as well as...
3
7415
by: thomson | last post by:
Hi all, Can sp_executesql used inside a user defined function, i tried but it has compiled well, but when i call the functio it shows Only functions and extended stored procedures can be executed...
1
460
by: LineVoltageHalogen | last post by:
Greetings All, currentley there is a heated discussion in my place of work over which method is better/more efficient for simple selects. Background: 1.) Simple Application that uses sql server...
7
7870
by: LineVoltageHalogen | last post by:
Greetings All, I have a very large query that uses dynamic sql. The sql is very large and it requires it to be broken into three components to avoid the nvarchar(4000) issue: SET @v_SqlString(...
1
8286
by: Matik | last post by:
Hi to all, Probably I'm just doing something stupid, but I would like you to tell me that (if it is so), and point the solution. There ist the thing: I' having a sp, where I call other sp...
1
8225
by: satishchandrat | last post by:
Hi, This is regarding the sp_executesql and the sql statement parameter, in processing a dynamic SQL on SQL Server 2000, in my stored procedure. I have my SQL string exeeding more than 4000...
5
3519
by: Yash | last post by:
Hi, I am using SQL 2000 SP4. I have compared 2 scenarios: Scenario 1: insert into #bacs_report SELECT ..... WHERE <conditions>
0
7234
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7136
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7344
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
7069
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
5652
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
5060
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
3203
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1570
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
441
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.