hi
I am trying to store the output of sp-executesql into a variable to implement it as a user defined function later
The function is
ALTER function [dbo].[UnitsAvailable] (@id int)
returns
intas
begin
declare
@sql nvarchar(100)declare
@params nvarchar(500)declare
@count nvarchar(10)set
@sql = N'Select count(*) from units where projectid=' + convert(varchar,@id) + 'and sold=0 and displayunit=1'set
@params = N'@countOUT nvarchar(10) OUTPUT';exec
sp_executesql @sql, @params, @countOUT=@count OUTPUT;return
@countend
The result is that I am able to parameterize the sql end execute with the right result. The only problem is that the value is not stored in the variable @count. I could get to the same result using managed code in sql 2005 but still I am curious to find out where the problem is ....Can you please help
Thanks Alex

Store the output of executesq
Manikandan MSFT
Sajith
Thaks! I just got the error message. So this would be an example of when to use managed code :))
Imports
SystemImports
System.DataImports
System.Data.SqlClientImports
System.Data.SqlTypesImports
Microsoft.SqlServer.ServerPartial
Public Class UserDefinedFunctions<SqlFunction(DataAccess:=DataAccessKind.Read)> _
Public Shared Function UnitsAvailable(ByVal ID As SqlInt32) As Integer
Using con As New SqlConnection("context connection=true")
Dim cmdText As String = "Select count(*) as UnitCount from units where projectid=" & ID.ToString & " and sold=0 and displayunit=1"
Dim cmd As New SqlCommand(cmdText, con)
con.Open()
Return CType(cmd.ExecuteScalar, Integer)
End Using
End Function
End Class
Alan1203
One stop further.
Here it works:
declare
@id intset
@id = 195declare
@sql nvarchar(100)declare
@params nvarchar(500)declare
@count nvarchar(10)set
@sql = N'Select @countOUT = count(*) from units where projectid=' + convert(varchar,@id) + 'and sold=0 and displayunit=1'set
@params = N'@countOUT nvarchar(10) OUTPUT';exec
sp_executesql @sql, @params, @countOUT=@count OUTPUT;select
@count Here it still produces no outputALTER
function [dbo].[UnitsAvailable] (@id int)returns
intas
begin
declare
@sql nvarchar(100)declare
@params nvarchar(500)declare
@count nvarchar(10)set
@sql = N'Select @countOUT = count(*) from units where projectid=' + convert(varchar,@id) + 'and sold=0 and displayunit=1'set
@params = N'@countOUT nvarchar(10) OUTPUT';exec
sp_executesql @sql, @params, @countOUT=@count OUTPUT;return
@countend
Kapil Singhal
>>ALTER function [dbo].[UnitsAvailable] (@id int)
You are not allowed to execute any procedures other than extended from within a function! It will never work.
Lee Meyers