User Defined Aggregate Function In SQL Server 2000?

Feb 19, 2008

Is it possible to define your own function? If so could you give me an example.

Keep in mind that I said in SQL Server 2000. I want no CLR SQL Server 2005 solutions.

Cheers,
David

View 1 Replies


ADVERTISEMENT

CLR User Defined Aggregate Function

Oct 4, 2006

I am trying to modify the C# example given in the "Invoking CLR User-Defined Aggregate Functions" in SQL Server 2005 Books Online. I want to add a parameter that is used as the list delimeter, instead of the hard coded comma that is used. I am not a C# programmer and don't know where to begin. Please help!

using System;
using System.Data;
using Microsoft.SqlServer.Server;
using System.Data.SqlTypes;
using System.IO;
using System.Text;

[Serializable]
[SqlUserDefinedAggregate(
Format.UserDefined, //use clr serialization to serialize the intermediate result
IsInvariantToNulls = true, //optimizer property
IsInvariantToDuplicates = false, //optimizer property
IsInvariantToOrder = false, //optimizer property
MaxByteSize = 8000) //maximum size in bytes of persisted value
]
public class Concatenate : IBinarySerialize
{
/// <summary>
/// The variable that holds the intermediate result of the concatenation
/// </summary>
private StringBuilder intermediateResult;

/// <summary>
/// Initialize the internal data structures
/// </summary>
public void Init()
{
this.intermediateResult = new StringBuilder();
}

/// <summary>
/// Accumulate the next value, not if the value is null
/// </summary>
/// <param name="value"></param>
public void Accumulate(SqlString value)
{
if (value.IsNull)
{
return;
}

this.intermediateResult.Append(value.Value).Append(','); /// I want to change to comma to a variable
}

/// <summary>
/// Merge the partially computed aggregate with this aggregate.
/// </summary>
/// <param name="other"></param>
public void Merge(Concatenate other)
{
this.intermediateResult.Append(other.intermediateResult);
}

/// <summary>
/// Called at the end of aggregation, to return the results of the aggregation.
/// </summary>
/// <returns></returns>
public SqlString Terminate()
{
string output = string.Empty;
//delete the trailing comma, if any
if (this.intermediateResult != null
&& this.intermediateResult.Length > 0)
{
output = this.intermediateResult.ToString(0, this.intermediateResult.Length - 1);
}

return new SqlString(output);
}

public void Read(BinaryReader r)
{
intermediateResult = new StringBuilder(r.ReadString());
}

public void Write(BinaryWriter w)
{
w.Write(this.intermediateResult.ToString());
}
}

View 4 Replies View Related

Like A User Defined Aggregate Function For Concate

May 8, 2008

Hi,

I have a table T1 with two fields. Field1 has repeated values and Field2 has unique values for any given Field1 value. F1 can have maybe 1000 different values while F2 maybe 20.

I would like to create a T2 table where Field1 has unique values and Field2 contains the concatenation of T1.Field1 values for each Field1 value.

T1
F1F2
1a
1b
2a
2c
2d

T2
F1F2
1ab
2acd

It is like a user defined aggregate function for concatenation. Any idea?

Cornelius

View 2 Replies View Related

Managed C++ User-defined Aggregate Function

Mar 16, 2007

Hi all,

I'm attempting to write an aggregate function in C++ to compare performance with the equivalent function in C#.

However, I'm having problems getting SQL Server to see the function in the assembly. It allows me to load the assembly into the database, but I can't see the type in it.

Here's my code:

// CPPTest.h

#pragma once

using namespace System;
using namespace Microsoft::SqlServer::Server;
using namespace System::Data::SqlTypes;
using namespace System::Data::SqlClient;

namespace CPPTest {

[Serializable]
[Microsoft::SqlServer::Server::SqlUserDefinedAggregate(
Format::Native,
Name="AGG_CPP_OR")]
public ref struct AGG_CPP_OR
{
public:
void Init();
void Accumulate(SqlInt32 Value);
void Merge(AGG_CPP_OR^ Group);
SqlInt32 Terminate();

private:
SqlInt32 m_accum;
};

}


// CPPTest.cpp

#include "stdafx.h"

#include "CPPTest.h"

void CPPTest::AGG_CPP_OR::Init()
{
m_accum = 0;
}

void CPPTest::AGG_CPP_OR::Accumulate(SqlInt32 Value)
{
m_accum = m_accum | Value;
}

void CPPTest::AGG_CPP_OR::Merge(CPPTest::AGG_CPP_OR^ Group)
{
m_accum = m_accum | Group->m_accum;
}

SqlInt32 CPPTest::AGG_CPP_OR::Terminate()
{
return m_accum;
}

Compile it with /clr:safe option and it can be loaded as an assembly into SQL Server 2005 (9.0.1399), but the AGG_CPP_OR type is not seen as an aggregate function. I've also tried implementing IBinarySerialize and setting Format to Format::UserDefined (and putting in MaxByteSize) but it makes no difference.

Does anyone know what I'm missing here?

Many thanks,

View 1 Replies View Related

Cannot Find Either Column Dbo Or The User-defined Function Or Aggregate Dbo.FN_NIVELCOMPETENCIACARGO, Or The Name Is Ambiguo

May 4, 2006

Hello i have this query and I havent been able to solve it

Cannot find either column "dbo" or the user-defined function or aggregate "dbo.FN_NIVELCOMPETENCIACARGO", or the name is ambiguous.

I have tried with dbo and withou dbo, specifyng columns inside it,



Thanks

select a.nmempresa,a.nmtipocompetencia, d.dsnombreciclo, c.dsnombrecargo,a.dstipocompetencia, a.dscatalogo,

b.popeso as PesoTipoCompetencia, f.dsnombrecompetencia as Competencia, e.pocompetencia as PesoCompetencia,

g.DSOPCIONESCALA, g.PESO

from

tgsc_tiposcompetencias a, TGSC_TIPOSCOMPETENCIASxcargo b, tgsc_cargos c, tgsc_ciclos d,

tgsc_competenciasxcargo e, tgsc_competencias f,

(select

dbo.FN_NIVELCOMPETENCIACARGO(a.nmempresa,a.nmciclo, a.nmtipocompetencia,c.nmcargo,f.nmcompetencia)) as g

where a.nmempresa=72 and a.nmciclo=9

and b.nmtipocompetencia=a.nmtipocompetencia

and b.nmcargo=10 and b.nmempresa=72 and b.nmciclo=9

and c.nmcargo=10 and c.nmempresa=72 and c.nmciclo=9 and d.nmciclo=9

and e.nmcargo=10 and e.nmciclo=9 and e.nmempresa=72

and f.nmcompetencia=e.nmcompetencia and f.nmtipocompetencia=a.nmtipocompetencia

and f.nmtipocompetencia=b.nmtipocompetencia

View 7 Replies View Related

User Defined Aggregate Problem

Feb 22, 2008

I am trying to get a random value from a select statement. The only way I thought to do this would be to make a User Defined Aggregate Function at returns one of the rows at random. For example MIN(column) return the minimum value of that column, MAX(column) returns the maximum. I would like something like RANDOM(column) to return one of the values at random.

For example: select RANDOM(Name) from Names

So I went and created a user defined aggregate function:




Code Snippet

Imports System

Imports System.Data

Imports System.Data.SqlClient

Imports System.Data.SqlTypes

Imports Microsoft.SqlServer.Server



<Serializable()> _

<Microsoft.SqlServer.Server.SqlUserDefinedAggregate(Format.Native)> _

Public Structure GetRandom

Public s As SqlString

Public x As Integer

Public Sub Init()

x = 0

Randomize()

End Sub

Public Sub Accumulate(ByVal value As SqlString)

s = New SqlString(s.ToString & "|" & value.ToString)

x = x + 1

End Sub

Public Sub Merge(ByVal value As GetRandom)

End Sub

Public Function Terminate() As SqlString

Dim d() As String = {"|"}

Return New SqlString(s.ToString.Split(d, StringSplitOptions.RemoveEmptyEntries)(Rnd() * x))

End Function

End Structure



The problem is that it wont deploy to the SQL Server because the varible "s" is not serilizable. Here is the error message:

Type "GetRandomFunction.GetRandom.GetRandom" is marked for native serialization, but field "s" of type "GetRandomFunction.GetRandom.GetRandom" is not valid for native serialization.

Can any help me with this? Is there any other way of storing the strings that will work?

Thanks,
Stuart Fox

View 1 Replies View Related

CLR User-defined Aggregate Support Java/J#?

May 18, 2006

I want to write a Java User-defined aggregate (UDA). Shall I use J#?

I converted the C# example given in books online to J#. I am getting this error (as well as whole bunch of warning when I create the assembly.)

Msg 6558, Level 16, State 1, Line 1

CREATE AGGREGATE failed because type 'Concatenate' does not conform to UDAGG specification due to method 'Init'.

Msg 6597, Level 16, State 2, Line 1

CREATE AGGREGATE failed.

btw, I have the use unsafe assembly options when creating the assembly otherwise I get this error:

Msg 6265, Level 16, State 1, Line 1

CREATE ASSEMBLY failed because type "com.ms.vjsharp.cor.COMUtils" in safe assembly "vjscor" has a pinvokeimpl method. P/Invoke is not allowed in safe assemblies.

Warning: The Microsoft .Net frameworks assembly 'vjscor, version=2.0.0.0, culture=neutral, publickeytoken=b03f5f7f11d50a3a, processorarchitecture=x86.' you are registering is not fully tested in SQL Server hosted environment.

From the warning, I can tell the J# UDA is not tested.

Can someone confirm whether J# UDA is supported or not?

Thanks!

-------------------------

Here is my code:

ALTER DATABASE MEDIO set TRUSTWORTHY ON

CREATE ASSEMBLY MyAgg FROM 'C:codeconsolePriceUDAobjDebugPriceUDA.dll' WITH PERMISSION_SET = unsafe

CREATE AGGREGATE MyAgg (@input nvarchar(200)) RETURNS nvarchar(max) EXTERNAL NAME MyAgg.Concatenate

GO

---------------------------------------

import System.*;

import System.Data.*;

import Microsoft.SqlServer.Server.*;

import System.Data.SqlTypes.*;

import System.IO.*;

import System.Text.*;

/** @attribute Serializable() */

/** @attribute SqlUserDefinedAggregate(

Format.UserDefined, //use clr serialization to serialize the intermediate result

IsInvariantToNulls = true, //optimizer property

IsInvariantToDuplicates = false, //optimizer property

IsInvariantToOrder = false, //optimizer property

MaxByteSize = 8000) //maximum size in bytes of persisted value

*/

public class Concatenate implements IBinarySerialize

{

/// <summary>

/// The variable that holds the intermediate result of the concatenation

/// </summary>

private StringBuilder intermediateResult;

/// <summary>

/// Initialize the internal data structures

/// </summary>

public void Init()

{

this.intermediateResult = new StringBuilder();

}

/// <summary>

/// Accumulate the next value, not if the value is null

/// </summary>

/// <param name="value"></param>

public void Accumulate(SqlString value)

{

if (value.get_IsNull())

{

return;

}

this.intermediateResult.Append(value.get_Value()).Append(',');

}

/// <summary>

/// Merge the partially computed aggregate with this aggregate.

/// </summary>

/// <param name="other"></param>

public void Merge(Concatenate other)

{

this.intermediateResult.Append(other.intermediateResult);

}

/// <summary>

/// Called at the end of aggregation, to return the results of the aggregation.

/// </summary>

/// <returns></returns>

public SqlString Terminate()

{

String output = String.Empty;

//delete the trailing comma, if any

if (this.intermediateResult != null

&& this.intermediateResult.get_Length() > 0)

{

output = this.intermediateResult.ToString(0, this.intermediateResult.get_Length() - 1);

}

return new SqlString(output);

}

public void Read(BinaryReader r)

{

intermediateResult = new StringBuilder(r.ReadString());

}

public void Write(BinaryWriter w)

{

w.Write(this.intermediateResult.ToString());

}

}

View 6 Replies View Related

How To Run User Defined Function On Sql Server 2005

Dec 24, 2007

Dear all
I wants to run sql server user defined function when linked two server.
 
I have linked two sql server.There is one function called getenc().This function created on first server.What i want.I wants to run this user defined function on the second sql server. can any one help me?
 
Regards
Jerminxxx

View 7 Replies View Related

Calling User Defined Function From Other Server

May 25, 2006

I have UDF in a database on SQL2000 server. Is it possible to call this UDF from other server (SQL2005)? I did setup a linked server to SQL2000

Call to the following function returns an error:

Msg 207, Level 16, State 1, Line 1

Invalid column name 'srv2000'.

select [srv2000].db_test.dbo.F_TEST()

View 4 Replies View Related

C# User Defined Function: Is There A Way To Access The Name Of The Sql Server?

Apr 26, 2006

This is my problem: I do not know how to get the servername from a C# user defined function . Is this possible?

I am writing a User Defined Function (UDF). Inside of this user defined function I need the name of the databaseserver that it is running on. Does anyone have an idea how I might do this? Is there an enviromental variable that I could access within the C# code I use to write the UDF?

I could always use a parameter to pass in the name of the server, but I would like to have as few parameters as possible.

Thanks in advance,

Sean

View 4 Replies View Related

SQL Server 2012 :: Using User Defined Function In View?

Jan 31, 2014

I have a function that accespts a string and a delimeter returns the results in a temp table. I am using the funtion for one of the columns in my view that needs be to split and display the column into different columns. The view takes for ever to run and finally it doesn't split and doesn't display in the column.

Function:
-----------------------------------
ALTER FUNCTION [dbo].[func_Split]
(
@DelimitedString varchar(8000),

[Code].....

Not sure what I am missing in the above view why it doesn't split the string.

View 8 Replies View Related

Retrieve The Version Of SQL Server From Within A User Defined Function

Sep 12, 2006

EXEC master.dbo.xp_msver ProductVersion can be used to return the server version in a resultset.  I need this to do some conditional coding between varchar and varchar(max) in a UDF, so size of the text I return must be different between the SQL2000 and SQL2005.

I cant call an xp_ that returns a resultset within a UDF can I, so how can I get the SQL version?

View 4 Replies View Related

SQL Server User Defined Function Treating String As Integer

Oct 3, 2006

I have a User Defined Function in my SQL Server 2000 database which takes a string and adds an integer quantity to it.  The function basically takes the string (string because of first character and spaces) and adds an integer to it creating a new number (starting number and ending number concept).If I pass in a string that has a letter for the first character, it works fine.  However, if the first character is an integer it trims out all 0s and whitespace and ruins the necessary formatting.  Note, the formatting is always the same - x xxx xxxx xx.   Any help or ideas would be appreciated.Example:D 499 8900 01     plus a Quantity of 10 returns D 499 89000 11  which is perfect.However,0 076 0000 03     plus a Quantity of 1 returns  764  764     (it should be 0 076 0000 04)------------------------------------CREATE FUNCTION  [dbo].[NEW_End_NR2](  @OldStr as char(20), @Quantity int )RETURNS @NewNR_Tbl TABLE (New_EndNr char(20) primary key)AS  BEGIN DECLARE @NewStr  char(20)  DECLARE @addNr  integerBEGIN  Set @addNr = @Quantity set @NewStr = (select REPLACE(@OldStr,left(@OldStr, 1),'')) set @NewStr = (select REPLACE(@NewStr,' ', ''))  + @addNr set @NewStr = (SELECT left(@OldStr, 1) +    SPACE(1) + left(@NewStr,3) +    SPACE(1) + left(REPLACE(@NewStr, left(@NewStr,3), ''), 4) +   SPACE(1) + left(REPLACE(@NewStr, left(@NewStr,7), ''), 3)) BEGIN  INSERT INTO @NewNR_Tbl (New_EndNr) VALUES(@NewStr) END END    RETURNEND

View 3 Replies View Related

SQL Server 2014 :: User Defined Function - Using Table Name As Variable

Aug 9, 2014

I'm trying to create a simple function that will do a count on a table. I want to pass the table name in form of a parameter to the variable and this function will return the count as an int. See my function below...

CREATE FUNCTION count_rows (@tablename varchar(100)
RETURNS int AS
BEGIN
DECLARE @emp_count AS int
declare @declaration varchar(100)

[Code] ....

The errors I am getting are as follows:

Msg 102, Level 15, State 1, Procedure count_rows, Line 3
Incorrect syntax near 'RETURNS'.
Msg 102, Level 15, State 1, Procedure count_rows, Line 10
Incorrect syntax near '@declaration'.
Msg 178, Level 15, State 1, Procedure count_rows, Line 14

A RETURN statement with a return value cannot be used in this context.

View 9 Replies View Related

A .NET Framework Error Occurred During Execution Of User-defined Routine Or Aggregate -While Creating A SQL SERVER 2005 Stored Prodecure In VS.NET 2005

Aug 15, 2007

 Running [dbo].[insertlogin] ( @log = hiten, @pas = hiten ).A .NET Framework error occurred during execution of user-defined routine or aggregate "insertlogin": System.Data.SqlClient.SqlException: Must declare the scalar variable "@Log".System.Data.SqlClient.SqlException:    at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)   at System.Data.SqlClient.SqlInternalConnectionSmi.EventSink.ProcessMessagesAndThrow(Boolean ignoreNonFatalMessages)   at Microsoft.SqlServer.Server.SmiEventSink_Default.ProcessMessagesAndThrow(Boolean ignoreNonFatalMessages)   at System.Data.SqlClient.SqlCommand.RunExecuteNonQuerySmi(Boolean sendToPipe)   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()   at SqlServerProject1.StoredProcedures.insertlogin(SqlString log, SqlString pas).No rows affected.(0 row(s) returned)@RETURN_VALUE = Finished running [dbo].[insertlogin]. ***************************************************************all i am trying to do is :  creating a SP in VS using managed code and then trying to execute it. But every time i get the above error. If you can tell me how to edit connection string in this that would be very helpful. At present i am using :   Using conn As New SqlConnection("context connection=true") I tried to do "" ALTER ASSEMBLY SqlServerProject1 WITH PERMISSION_SET=EXTERNAL_ACCESS""but i get this error  ""  Msg 10327, Level 14, State 1, Line 1ALTER ASSEMBLY for assembly 'SqlServerProject1' failed because assembly 'SqlServerProject1' is not authorized for PERMISSION_SET = EXTERNAL_ACCESS.  The assembly is authorized when either of the following is true: the database owner (DBO) has EXTERNAL ACCESS ASSEMBLY permission and the database has the TRUSTWORTHY database property on; or the assembly is signed with a certificate or an asymmetric key that has a corresponding login with EXTERNAL ACCESS ASSEMBLY permission. If you have restored or attached this database, make sure the database owner is mapped to the correct login on this server. If not, use sp_changedbowner to fix the problem.""" *********************************************************************Plz help 

View 13 Replies View Related

SQL Server 2012 :: Convert Stored Procedure To User Defined Function?

Feb 23, 2015

I have created a store procedure, but the requirement is function because by using this function we need to add columns in a table with SSIS.

I have tried to create function, but the error I am facing is select statement can not return data.

CREATE PROCEDURE SP_STAT_CURR
(
@I_NET_AMOUNT NUMERIC(10,3),
@I_DOCUMENT_CURR VARCHAR(3),
@I_TARGET_CURR VARCHAR(3)

[code]....

View 9 Replies View Related

SQL 2012 :: NET Framework Error Occurred During Execution Of User-defined Routine Or Aggregate

Aug 4, 2015

when i try to deploy a packages in integration service catalog i am getting the below error

.NET Framework error occurred during execution of user-defined routine or aggregate

"deploy_project_internal":

System.ComponentModel.Win32Exception: A required privilege is not held by the client

System.ComponentModel.Win32Excepbon:

at Microsoft. SqlServer. IntegrationServices.Server.ISServerProcess.StartProcess(Soolean

bSuspendThread)

at Microsoft.SqlServer.IntegrationServices.Server.ServerApi.DeployProjectlnternal(SqlInt64 deployld,

SqIInt64 versionld, SqlInt64 projectld, SqlString projectName)

. (Microsoft SQL Server, Error: 6522)

View 0 Replies View Related

User Defined Funcyions In Sql Server 2000

Oct 14, 2006

hi,it might be a very stupid question but i want to know whether anexecution plan is created in user defined functions in sql server 2000like stored procedures.Thanks.

View 4 Replies View Related

Help Convert MS Access Function To MS SQL User Defined Function

Aug 1, 2005

I have this function in access I need to be able to use in ms sql.  Having problems trying to get it to work.  The function gets rid of the leading zeros if the field being past dosn't have any non number characters.For example:TrimZero("000000001023") > "1023"TrimZero("E1025") > "E1025"TrimZero("000000021021") > "21021"TrimZero("R5545") > "R5545"Here is the function that works in access:Public Function TrimZero(strField As Variant) As String   Dim strReturn As String   If IsNull(strField) = True Then      strReturn = ""   Else      strReturn = strField      Do While Left(strReturn, 1) = "0"         strReturn = Mid(strReturn, 2)      Loop   End If  TrimZero = strReturnEnd Function

View 3 Replies View Related

Using RAND Function In User Defined Function?

Mar 22, 2006

Got some errors on this one...

Is Rand function cannot be used in the User Defined function?
Thanks.

View 1 Replies View Related

Help With User Defined Function

Jan 10, 2007

I have a UDF that takes my input and returns the next valid business day date. My valid date excludes weekends and holidays.
It works perfect except for one issue. It doesn't check to see if today's date  is a holiday.
I pass a query to sql server like so " select dbo.getstartdate('01/ 10/2007',2)"
It then moves ahead two business days and returns that date.
Here is the current code. Hopefully someone can tell me how to do the holiday check on the current date.
I really don't want to rewrite the whole script .
Code---------------------------------------------------------
SET QUOTED_IDENTIFIER OFF GOSET ANSI_NULLS OFF GO
--DROP FUNCTION GetStartDate
--declare function receiving two parameters ---the date we start counting and the number of business days
CREATE  FUNCTION GetStartDate (@startdate datetime, @days int)   RETURNS datetimeASBEGIN
--declare a counter to keep track of how many days are passingdeclare @counter int
/*Check your business rules.  If 4 business days means you count starting tomorrow, set counter to 0.  If you start counting today, set counter to 1*/set @counter = 1
--declare a variable to hold the ending datedeclare @enddate datetime
--set the end date to the start date.  we'll be -- incrementing it for each passing business dayset @enddate = @startdate
/*Start your loop.While your counter (which was set to 1), is less than or equal to the number of business days increment your end date*/WHILE @counter <= @days
BEGIN
--for each day, we'll add one to the end dateset @enddate = DATEADD(dd, 1, @enddate)
   --If the day is between 2 and 6 (meaning it's a week   --day and the day is not in the holiday table, we'll    --increment the counter   IF (DATEPART(dw, @enddate) between 2 and 6) AND       (@enddate not in           (           select HolidayDate            from tFederalHoliday            where [HolidayYear] = datepart(yyyy,@enddate)         )       )   BEGIN      set @counter = @counter + 1   END
--end the while loopEND
--return the end dateRETURN @enddate
--end the functionEND
GOSET QUOTED_IDENTIFIER OFF GOSET ANSI_NULLS ON GO
---------------------------------------------------------------------------------------------

View 1 Replies View Related

User Defined Function

Aug 17, 2005

Hi everyone,
    I am tring to pass acomma delimited string to a function  and this function is parsing the string so that I can see individual values so for example I am passing 1,2,3,4,5 as a parameter to my function and I am parsing this string so that I can write something like this
Select * from tableA where userID in(1,2,3,4)
It is working fine. Only problem is if the user passes word 'all' instead of 1,2,3,4 then I have to doSelect * from tableA
My function looks like this.  How can I modify this function if I pass 'all' as a paramater. Any help will be appreciated.CREATE FUNCTION [dbo].[ParseText2File] (@p_text varchar(4000), @p_Delimeter char(1))
RETURNS @results TABLE (id varchar(100))
AS
BEGIN
declare @i1 varchar(200)
declare @i2 varchar(200)
declare @tempResults Table (id varchar(100))
while len(@p_text) > 0 and charindex
(@p_Delimeter, @p_text) <> 0
begin
select @i1 = left(@p_text, charindex(@p_Delimeter, @p_text) - 1)
insert @tempResults select @i1
select @p_text = right(@p_text, len(@p_text) - charindex(@p_Delimeter,@p_text))
end
insert @tempResults select @p_text
insert @results
select *
from @tempResults
return
END
Thanks

View 1 Replies View Related

User Defined SQL Function

Dec 14, 1999

How can I create a user defined function in SQL and call it inline from a SQL statement? I need the ability to execute a statement such as:

select myFunc(x,y) from table

I need myFunc(x,y) to return a value, not a recordset and use that value in the select statement. Any and all ideas would be appreciated.

View 1 Replies View Related

User Defined Function

Aug 2, 1999

Dear friends,

I am a new user for SQL server. Coming from an oracle background, I find it very difficult to live without user defined functions. At the moment, I urgently need to have a function returning an custom-made ID string, so that it can be used in one of my stored procedures. I have heard the rumours that SQL server 7 does NOT support user defined functions, (which SQL 6.5 does). I would be really grateful if anyone can clarify this for me, and if possible, suggest a get-around approach.

Thanks in advance!

Kai

View 2 Replies View Related

User Defined Function Help!

Jun 23, 2004

I am trying to compare the data from one table (shipments) with the data from a view. The point of the function is to match the correct territory with the account depending on the data. Basically, I this deals with accounts that are transfering from one territory to another. The transfers take effect on the first day of the month, retroactive, therefore we need to allocate the sales data to the correct territory in the shipments table. Here is my function. Can someone tell me how I can get this to work and insert a territory ID for the account that has transfered into the shipments table?

CREATE FUNCTION fnShipments ()
RETURNS @Shipments TABLE (AccountID CHAR(10), DateInvoice DateTime, DollarShipments Money, TerritoryID CHAR(10))
AS
BEGIN
INSERT @Shipments (AccountID, DateInvoice, DollarShipments, TerritoryID)
SELECT Shipments.AccountID, Shipments.DateInvoice, DollarShipments, ISNULL((SELECT TerritoryID FROM vwAccountTransfers

WHERE Shipments.AccountID = vwAccountTransfers.AccountID

AND vwAccountTransfers.EffectiveMonth =

(SELECT MIN(EffectiveMonth)
FROM vwAccountTransfers

WHERE Shipments.AccountID = vwAccountTransfers.AccountID
AND DatePart(m,Shipments.DateInvoice) < vwAccountTransfers.EffectiveMonth)),
(SELECT TerritoryID FROM vwAccountTransfers
WHERE Shipments.AccountID = vwAccountTransfers.AccountID
AND vwAccountTransfers.EffectiveMonth Is Null )
) AS Territory
FROM Shipments

ORDER BY Shipments.AccountID, Shipments.DateInvoice;
RETURN
END

View 1 Replies View Related

User Defined Function

Nov 10, 2004

I need a UDF that will do the following:

User: Will be sending me a datetime e.g '9 Nov 2004 15:00:00'
I want the UDF to do the following for me
Return in hours the difference between what the user has send and now (lets say now = '10 Nov 2004 11:00:00')
So the UDF will return to me 20.
But I dont want 20, I want the UDF to avoid any all hours which are not work related (any time after 16h00
until 8h00 in the morning), so I want this UDF to return 4. That means from '9 Nov 2004 15:00:00' I have calculated
1hr until 16h00 and 3hrs from 8 until 11h00 on '10 Nov 2004 11:00:00'

AGAIN IT MUST NOT CALCULATE WEEKENDS. Lets say '12 Nov 2004 15:00:00' was Friday and now = '15 Nov 2004 11:00:00', I must still
get 4 as a return from UDF

I would also like now to be my getdate(), but it seems like you can't use it in UDF

View 1 Replies View Related

User Defined Function Help?

Mar 20, 2004

I create the following UDF just for learning purposes and I cannot seem to get it to return a value.

Stored Procedure

REATE PROCEDURE usp_GetXSection

@fWidth float,
@fHeight float,
@fResult float OUTPUT

AS
BEGIN
set @fResult = [dbo].[XSECTION](@fWidth, @fHeight)
END
GO


Ane the following UDF


CREATE FUNCTION XSECTION
(@Width float, @Height float)
RETURNS float
AS
BEGIN
RETURN (@Width * @Height)
END


I call it using ADO in a c++ application, but all returns empty

Any ideas? C++ code to follow.

Mike B


void CFormTemplateSetup::OnCalculate()
{
_CommandPtr pCmd(__uuidof(Command));
_ParameterPtr pWidth(__uuidof(Parameter));
_ParameterPtr pHeight(__uuidof(Parameter));
_ParameterPtr pResult(__uuidof(Parameter));

try
{
pCmd->ActiveConnection = GetDocument()->GetConnection();
pCmd->CommandText = _T("usp_GetXSection");
pCmd->CommandType = adCmdStoredProc;

_variant_t vWidth, vHeight;
vWidth.vt = VT_R4;
vHeight.vt = VT_R4;

vWidth.fltVal = 10;
vHeight.fltVal = 10;

pWidth = pCmd->CreateParameter(_T("@fWidth"), adInteger, adParamInput, sizeof(int), vWidth);
pHeight = pCmd->CreateParameter(_T("@fHeight"), adInteger, adParamInput, sizeof(int), vHeight);
pResult = pCmd->CreateParameter(_T("@fResult"), adDouble, adParamOutput, sizeof(float), vtMissing);

pCmd->Parameters->Append(pWidth);
pCmd->Parameters->Append(pHeight);
pCmd->Parameters->Append(pResult);

_variant_t vResult = pResult->Value;

float fArea = pResult->Value.fltVal;
CString csArea;
csArea.Format("Area = %d", fArea);

::AfxMessageBox(csArea);
}
catch(_com_error& e)
{
::AfxMessageBox(e.Description());
}
}

View 1 Replies View Related

User Defined Function

Apr 17, 2007

Hi,
Iam working on one user defined function which will take week & year as argument and returns sunday date of that particular week in that year. for example if i give (15,2007) as argument it shud give 2007-04-08 as result. Plz anybody help this on this issue.

View 13 Replies View Related

Need Help With User Defined Function

Apr 6, 2006

I am accustomed to doing most of my function work in Access, but the boss would really like it if I could shedule some cubes to do the stuff that takes forever when you run it live.

To that end, I have an Access function that I call to get a field value for a query. I would like to be able to create an User Defined Function on the SQL server and call that function as a field value in a view. I have searched the forums and have not really found anything that wants to make sense to me as to how to do this.

The access function is as follows:

Public Function BuyerDeltas(IFSDate As Date, PODate As Date) As Long

If IFSDate < (Date + 14) Then
BuyerDeltas = IFSDate - 3 - PODate
ElseIf IFSDate < (Date + 29) Then
BuyerDeltas = IFSDate - 7 - PODate
ElseIf IFSDate > (Date + 28) Then
BuyerDeltas = IFSDate - 10 - PODate
Else
MsgBox "This should not be possible!", vbOKOnly, "Fix It!!!!!!!"
End If

End Function

The view that this is called from contains the IFSDate and PODate fields and I am able to call the function from the access query, but this is completely different than what I have seen in the help files on SQL.

I would love to be able to keep plugging away at doing this myself, but the boss also is pushing me to get it done and he doesn't want me taking forever to do it.

Any direction would be greatly appreciated!

View 6 Replies View Related

Calling The User Defined Function!!!

Aug 28, 2007

hai,
the problem is - I have created a userdefined function using SQL 2000
create function  getfulldate (@date varchar(10))returns datetimeasbegindeclare @getfulldate datetime set @getfulldate  = dateadd (mi,55,@date)
return @getfulldateend
and normally we call this in the SQL statements as
select *, dbo.getfulldate('2006-05-03')  from emp
This works fine and what I need was, I need to invoke the user-defined function like
select *, getfulldate('2006-05-03')  from emp    that is, without using "dbo".
If I call in that manner, it gives error as - 'getfulldate' is not a recognized function name.
So, here what is the purpose of dbo and can I call in my desired manner as mentioned above.
anyone guide me, thanks!

View 3 Replies View Related

How To Exec SQL User Defined Function?

Aug 4, 2005

Hi,How to exec a SQL user defined function in query analyzer when it accepts parameters.. I know for a stored procedure we can write EXEC nameofstored procedure abc (@abc is the parameter passed).. But How to run a SQL function ?Thanks

View 2 Replies View Related

User Defined Function Problem

Feb 28, 2006

I have  a sproc that passes an ID to a user defined function. I just realized that the udf can only return scalar type value. I need it to return a varchar(10). How can i do this with similiar functionality. Any ideas?  

View 1 Replies View Related

GETDATE() With A User Defined Function

Jun 9, 2004

Hi,

I have a requirement where i need to get the current time/date within a Function. As getDate function is a non deterministic function it can not be used with in a function. Your guidence in this regard is greately appreciated.

Regards,
Samcute.

View 11 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved