I have to create a User Defined Function that returns a table as result.
I need to create this function from my c# application, but when I try to run the code against my DB SQL server gives me an error, but, when I run the same code from Management Studio it gives me no error and works fine.
This is what I have in C#
private const string FN_AXDBINFO =@"
CREATE FUNCTION FN_AXDBINFO ( )
RETURNS @SYS_DBINFO TABLE
(
SYSTEMTYPE VARCHAR(50) ,
COUNTRYCODE VARCHAR(10) ,
HLNUMBER VARCHAR(15) ,
VERSION VARCHAR(20) ,
DATO_SISTEMA VARCHAR(20)
)
AS
BEGIN
INSERT INTO @SYS_DBINFO
( SYSTEMTYPE ,
COUNTRYCODE ,
HLNUMBER ,
VERSION ,
DATO_SISTEMA
)
SELECT TOP 1
SYSTEMTYPE ,
COUNTRYCODE ,
HLNUMBER ,
VERSION ,
DATO_SISTEMA
FROM AXDBINFO
ORDER BY LAST_UPDATE DESC
RETURN
END
";
cmd = GetNewCommand(cc); //This function gets a new SQL COMMNAD
//object with an open sql server connection
//Add the command text from de const
cmd.CommandText =FN_AXDBINFO;
//Execute
cmd.ExecuteNonQuery();
/// <summary>
/// Obtiene un nuevo SqlCommand
/// </summary>
/// <returns></returns>
protected SqlCommand GetNewCommand(CustomConnection cc)
{
SqlCommand cmd;
SqlConnection conn = new SqlConnection(Utils.Utils.GetConnectionString(cc));
cmd = conn.CreateCommand();
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.CommandType = CommandType.Text;
return cmd;
}
And this is the error that i get when run the aplication:
Incorrect syntax near the keyword 'FUNCTION'. Must declare the table variable "@SYS_DBINFO".
The thing is that the same TSQL code from Management studio works just fine. I try the folowing:
- Add a parameter called @SYS_DBINFO, the error changes to
incorrect syntax near the keyword 'FUNCTION'
Put @SYS_DBINFO beteween brackets, get the same error.
Try to create a UDF using SMO, but it is not compatible with previous version of SQL SERVER
Can anyone help me with this please?
Thanks.
To avoid confusion, I have edited the code, the error remains the same. I can not create a table-type UDF since SQL SERVER assumes that the table that results from the function whose name is @SYS_DBINFO is a scalar variable, and again, the same code from MANAGEMENT STUDIO works fine.