Set my function as Default - sql

i have function and i want to create it as default
ALTER FUNCTION [dbo].[ModifiedBy]()
RETURNS varchar(50)
AS
BEGIN
RETURN host_name()
END
I want to do something like this, but it doesnt work. is it possible?
create default default_modifiedBy AS dbo.ModifiedBy()
Eror is User-defined functions, partition functions, and column references are not allowed in expressions in this context.

I have just tried doing this and it works fine for me:
CREATE FUNCTION [dbo].[ModifiedBy]()
RETURNS varchar(50)
AS
BEGIN
RETURN host_name()
END
GO
CREATE TABLE Test (
ID INT
, Hostname VARCHAR(50) DEFAULT ([dbo].[ModifiedBy]())
);
GO
Test
INSERT INTO dbo.Test ( ID )
VALUES ( 1 )
SELECT * FROM dbo.Test

From the MSDN page for create default:
Any constant, built-in function, or mathematical expression can be
used, except those that contain alias data types. User-defined
functions cannot be used
Like M.Ali writes, you can use a user-defined function if you create a column-bound default constraint with alter table ... add constraint or create table ... (col1 default dbo.MyFunc());.

Related

Linked Table Valued Function Parameters (SQL Server)

I need to create a SQL Server TVF that takes a single param and then used that param to build the other required parameters. Is this even possible?
The error states incorrect syntax near 'LEFT'. Simple representation below.
CREATE FUNCTION TESTFUNCTION
(
-- Add the parameters for the function here
#PRM1 VARCHAR(2) = 'ABC',
#PRM2 VARCHAR(1) = LEFT(#PRM1,1)
)
RETURNS TABLE
AS
RETURN
(
-- Add the SELECT statement with parameter references here
SELECT #PRM2
)
GO
Thank You!
BEFORE EDIT MADE IN THE QUESTION :
You need only one parameters :
SELECT #PRM2 = LEFT(#PRM1, 1);
However, you need scaler function not table valued function :
CREATE FUNCTION TESTFUNCTION
(
-- Add the parameters for the function here
#PRM1 VARCHAR(2) = 'ABC'
)
RETURNS VARCHAR(255)
AS
BEGIN
DECLARE #PRM2 VARCHAR(255)
SET #PRM2 = LEFT(#PRM1, 1)
RETURNS (#PRM2)
END
Note : Your #PRM1 will accept only two characters which are AB. So, define appropriate length.

Return table valued function return table structure like my actual table using Sql Server 2008?

I have a table named tableincentive like below
create table tableincentive (entry_date date,ag_id int,us_id int,lo_id int,loin_id int,de_id int,dest_id int,incentive_amt decimal(18,2),le_id int,lion_id int,etc...)
And i have a table valued function named [dbo].[func_getdetails]
Create FUNCTION [dbo].[func_getdetails]
(
-- Add the parameters for the function here
#ason_date date
)
RETURNS
#tableincentive TABLE
(
-- Add the column definitions for the TABLE variable here
entry_date date,ag_id int,us_id int,lo_id int,loin_id int,de_id int,dest_id int,incentive_amt decimal(18,2),le_id int,lion_id int,etc...
)
AS
BEGIN
-- some long process then
insert into #tableincentive
select * from tableincentive;
end
My problem is the table tableincentive has 43 columns so i create a table valued function return tableincentive structure.I need return like my actual table.
that means in function
RETURNS
#tableincentive TABLE
(
-- Add the column definitions for the TABLE variable here
entry_date date,ag_id int,us_id int,lo_id int,loin_id int,de_id int,dest_id int,incentive_amt decimal(18,2),le_id int,lion_id int,etc...
)
AS
begin end
changed to
RETURNS tableincentive
AS
begin
end
or
RETURNS #tableincentive table like tableincentive
AS
begin
end
User Defined Functions need Static results. That means you have to define the return type while creating the function. So If you want to have a static result set, then probably you should opt for a stores Procedure.

DB2 SQL Function with dynamic return value

I have the following working DB2 SQL function
CREATE OR REPLACE FUNCTION selector (param VARCHAR(3))
RETURNS TABLE (id INT, CMD VARCHAR(1024), ATTR CHAR(10))
LANGUAGE SQL
DETERMINISTIC
NO EXTERNAL ACTION
RETURN
SELECT id, cmd, attr
FROM test.commandtbl c
WHERE c.attr=param;
Calling it like:
select * from table (selector('c'))!
The problem is that I want the return table to be dynamic in size and type.
I want to use the function with a lot of return fields and and while testing I don't want to always check the return table it everything still matches.
For example:
Test1 is with 5 return columns: INT, INT, INT, CHAR(10), VARCHAR(100)
Test2 is with 20 return columns: 10 VARCHAR(100) and 10 INT
and so on.
Is there a way to do that?
You can consider SQL a statically typed language in that it has little ability to discover its variable (e.g. column) and object (e.g. result set) data types at run time; you have to declare types at the statement compilation time. In other words, what you want to achieve is not possible.
There is a concept of a generic table function which allows you to define a Java-based UDF that returns some result set:
CREATE FUNCTION selector (param VARCHAR(3))
RETURNS GENERIC TABLE
EXTERNAL NAME...
However, you still need to declare the result set structure on the receiving end:
SELECT t.* FROM TABLE (selector('c')) AS t (foo INT, bar INT, baz VARCHAR(10)...)

How do I return a scalar variable from a select statement

I am altering a table by adding a new column, this column must have a default value taken from a single entry in another table
ALTER TABLE Bonus_Profile
ADD Orgunit varchar(50) NOT NULL
DEFAULT (select top 1 OrgUnit from OrgUnits where ReportTo is null)
The above statement gives Subqueries are not allowed in this context. Only scalar expressions are allowed. as and error
What should be used to get a scalar variable of OrgUnit
Create a parameterless scalar function first
CREATE FUNCTION ReturnOrgUnit ()
RETURNS VARCHAR(50)
BEGIN
Declare #orgUnit varchar(50)
Select TOP 1 #orgUnit= OrgUnit from OrgUnits where ReportTo is null
Return #orgUnit
END
Then you can use above udf in alter statement
ALTER TABLE Bonus_Profile
ADD Orgunit varchar(50) NOT NULL
DEFAULT (ReturnOrgUnit())

sql insert into table which uses newid in user defined function [duplicate]

I have to insert a fake column at the result of a query, which is the return value of a table-value function. This column data type must be unique-identifier. The best way (I think...) is to use newid() function. The problem is, I can't use newid() inside this type of function:
Invalid use of side-effecting or time-dependent operator in 'newid()' within a function.
here's a clever solution:
create view getNewID as select newid() as new_id
create function myfunction ()
returns uniqueidentifier
as begin
return (select new_id from getNewID)
end
that i can't take credit for. i found it here:
http://omnibuzz-sql.blogspot.com/2006/07/accessing-non-deterministic-functions.html
-don
You can pass NEWID() as a parameter to your function.
CREATE FUNCTION SOMEIDFUNCTION
(
#NEWID1 as varchar(36), #NEWID2 as varchar(36)
)
RETURNS varchar(18)
AS
BEGIN
-- Do something --
DECLARE #SFID varchar(18)
SELECT #SFID = 'DYN0000000' + LOWER(LEFT(#NEWID1,4)) + LEFT(#NEWID2,4)
RETURN #SFID
END
GO
Call the function like this;
SELECT dbo.SOMEIDFUNCTION(NewID(),NewID())
use it as a default instead
create table test(id uniqueidentifier default newsequentialid(),id2 int)
insert test(id2) values(1)
select * from test
NB I used newsequentialid() instead of newid() since newid() will cause pagesplits since it is not sequential, see here: Some Simple Code To Show The Difference Between Newid And Newsequentialid
You could use ROW_NUMBER function:
SELECT
(ROW_NUMBER() OVER (ORDER BY recordID) ) as RowNumber ,
recordID,
fieldBla1
FROM tableName
Find more information at http://msdn.microsoft.com/pt-br/library/ms186734.aspx