Using User Defined Functions For A Specific Database in SQL - sql

How I can use a user defined function for a specific database (The use db statement is not working). Here are the images for the table and the query
I can't understand the errors which i am getting here.
Please someone help.
I have only a single table for now in my database
[The Query][2]
Use Lab6
Create function fetch_orders (#P_Customer_ID int)
Returns int
AS
Begin
Return (Select Count (Order_ID)
From Orders
Where Customer_ID = #P_Customer_ID)
End

You need a GO after a USE statement:
USE Lab6
GO
CREATE FUNCTION ...

Related

using user-defined function for constraint in SQL

I am trying to add a check constraint to my table in SQL database so that user can only enter the work_group in the column that is in the 'approved list' - dbo.work_groups.
I've read a few forums and created the following table, user defined function and constraint.
dbo.work_groups is populated with the list of work groups, i.e. 'Admin','Accountant', 'Engineer'.
When I enter the above work groups into dbo.test it accepts them. But it also accepts any other values.
How can I limit the constraint only to those work groups that are listed in the dbo.work_groups.
What have I done wrong?
Thanks.
-----test table
CREATE TABLE [dbo].[test]
([testname] nvarchar NOT NULL)
-----user defined function
CREATE FUNCTION [dbo].[check_work_group](#testname NVARCHAR(50))
RETURNS NVARCHAR(50)
AS
BEGIN
RETURN (SELECT work_group FROM [dbo].[work_groups] WHERE work_group=#testname)
END;
-----constraint
ALTER TABLE test ADD constraint CK_testname
CHECK (testname=dbo.check_work_group(testname));
I think the issue with the function. When there is no record in the work_groups table for a given parameter value, it is returning null, which is causing the issue. One way to solve it is by forcing the function to return a value that does not exist in work_groups table ('-1' in the example below) when no record is found for the given parameter value.
CREATE FUNCTION [dbo].[check_work_group](#testname NVARCHAR(50))
RETURNS NVARCHAR(50) AS
BEGIN
RETURN COALESCE((SELECT work_group FROM [dbo].[work_groups] WHERE work_group=#testname), '-1');
END;

MSSQL Adding .ToString to datefields

i have some querys in my new SQL 2019 Database that connect to a table in a different database (MSSQL Server 2016) via linked servers.
But Everytime there is a date field in that query i get the error "The function or aggregat .ToString could not be found or the name is ambiguous".
I found that there is a hierarchy-ID-Function named "toString".
But i cant see why SQL should be using it when i dont call it to.
When i delete all Date fields from that query it executes without a problem.
SELECT * FROM [LinkedServerName].Databasename.integris.Tablename
EDIT:
I just noticed, that SQL somehow edits my text.
is what i wrote into the vieweditor.
is what the error shows me.
EDIT2: i set up the same linked server on an old SQL 2005 Server. Everything works fine. I guess because the 2005 server has no ToString() function... but im not sure.
I can construct a situation that would recreate the error, but I can't say for sure whether this is what is happening in your case. It's hard to demonstrate in a comment though, so I'll do as an answer.
Suppose we have a table t, with a computed column f, which references function dbo.f, which in turn references function dbo.g:
create function dbo.g() returns int as begin return 1 end;
go
create function dbo.f() returns int as begin return dbo.g(); end;
go
create table t(i int, f as dbo.f());
go
insert t(i) values (1);
select * from t;
go
So far so good. But now we drop function dbo.g and try to select from t:
drop function dbo.g;
select * from t;
This will result in the error: Cannot find either column "dbo" or the user-defined function or aggregate "dbo.g", or the name is ambiguous.
Look at the definition of the source table and check for computed columns, especially computed columns using nested constructs.

DB2: How to get generated always as statement to work with session user

I need to get a userstamp into a table and have not managed to figure out how the GENERATED FOR EACH ROW ON UPDATE AS statement works with the SESSION_USER variable in DB2 10.5 (LUW).
Managed to get an implementation working using a function which has a fake variable for forcing the evaluation in update statements:
CREATE OR REPLACE FUNCTION XXX.CURRENT_USER( tmp varchar(128))
SPECIFIC xxx.XXX_CURRENT_USER
RETURNS VARCHAR(128)
CONTAINS SQL DETERMINISTIC NO EXTERNAL ACTION
BEGIN
RETURN session_user ;
END
GO
CREATE TABLE xxx (
i INTEGER,
t VARCHAR(128) GENERATED ALWAYS AS (XXX.CURRENT_USER(i))
)
However, would be nice have less "hacky" implementation for a basic thing like this.
For the time stamps there is that "FOR EACH ROW ON UPDATE AS ROW CHANGE TIMESTAMP" statement but no equivalent for other register variables it seems.
Help is very much appreciated
Does this work?
CREATE TABLE xxx (
i INTEGER,
t VARCHAR(128) WITH DEFAULT session_user
);
I don't have DB2 on hand to check, but this is very similar to the syntax used in other databases (although the more typical syntax does not use WITH).

Why does this SQL stored procedure require that a temp table be created for it to work (return results)?

IBM Informix Dynamic Server Version 11.50.FC6
I was working on a small stored procedure that would take name fields from a table and parse them into "user names" with a maximum of 8 chars.
This is the code I was trying:
CREATE PROCEDURE build_jics_user (pid INT)
RETURNING CHAR(8) AS username;
SELECT LOWER((SUBSTR(firstname,0,1))||(SUBSTR(lastname,0,7))) username
FROM id_rec
WHERE id = pid;
END PROCEDURE;
The error returned when executed is:
659: INTO TEMP table required for SELECT statement.
Error in line 5
Near character position 15
I don't understand what the point of summoning a temporary table is, and I also couldn't find any similarly simple examples online that would work without error.
Does anyone know what I'm missing?
What you want to say is this:
CREATE PROCEDURE build_jics_user (pid INT)
RETURNING CHAR(8);
DEFINE username CHAR(8);
SELECT LOWER((SUBSTR(firstname,0,1))||(SUBSTR(lastname,0,7))) INTO username
FROM id_rec
WHERE id = pid;
RETURN username;
END PROCEDURE;
... and execute it like this:
EXECUTE PROCEDURE build_jics_user(42);
UPDATE
If the purpose of this is to be a function, where it's required inside some other SQL, then you might do the following:
CREATE FUNCTION jics_user(fname VARCHAR(255), lname VARCHAR(255))
RETURNING CHAR(8);
RETURN LOWER(SUBSTR(fname,0,1) || SUBSTR(lname,0,7));
END FUNCTION;
... and execute it like this:
SELECT id, firstname, lastname, jics_user(firstname, lastname) AS jics_user, ...
FROM id_rec;
There's no real technical difference between a PROCEDURE and a FUNCTION, it's more an assertion as to how it's used.
This seems to be per design (which must be accounting for the absence of the 'similarly simple examples online'). Apparently, whatever data you are pulling with a SELECT statement in a stored procedure, you cannot return them directly. You should store them either in a temporary table or in variables for later use.
It is likely that your SELECT statement should look like this
SELECT LOWER((SUBSTR(firstname,0,1))||(SUBSTR(lastname,0,7))) INTO username
FROM id_rec
WHERE id = pid;

Insert query in SQL Function

Can i write a insert query inside Function in SQL server 2008. If i tried, im a getting an error of Invalid use of side effecting operator 'INSERT' within the function. Please help me out. But i want it to be a function, not a stored procedure
Create function EFT_DL_FUNC_AUDTI_BATCH_START (#i_db_name varchar(20))
returns int as
begin
insert into table_name(db_name) values (#i_db_name)
return 0
end
Quote from here:
User Defined Functions cannot be used
to modify base table information. The
DML statements INSERT, UPDATE, and
DELETE cannot be used on base tables.
So you can't do an INSERT in a function.
You might want to explain WHY you don't want to use a procedure.