MSSQL Adding .ToString to datefields - sql

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.

Related

Trying to get HANA Create function to work in ODBC (warning in hdbsql becomes error in ODBC)

I have the following function that we have working in SQL Server, in PostGreSQL, and a version of this working in Oracle (not with a SELECT INTO but using a ref cursor).
Our function in HANA will compile with warnings on the hdbsql command line, but when executed within an ODBC call, it throws an exception. The database I'm using for testing is (unfortunately) a Version 1 db.
CREATE OR REPLACE FUNCTION GETWFFIELD
(
IN TABLENAME VARCHAR,
IN FIELDNAME VARCHAR,
IN LANGCODE VARCHAR,
IN WORKID DECIMAL,
IN SUBWORKID DECIMAL,
IN TASKID DECIMAL,
IN DEFVAL VARCHAR
) RETURNS SQLResults NVARCHAR(2000)
AS
BEGIN
IF TASKID IS NULL THEN
SELECT TOP 1 Value
INTO SQLResults DEFAULT DEFVAL
FROM WML
WHERE TableName=TABLENAME
AND ColName=FIELDNAME
AND Key1=WORKID
AND Key2=SUBWORKID
AND LangCode=LANGCODE;
ELSE
SELECT TOP 1 Value
INTO SQLResults DEFAULT DEFVAL
FROM WML
WHERE TableName=TABLENAME
AND ColName=FIELDNAME
AND Key1=WORKID
AND Key2=SUBWORKID
AND Key3=TASKID
AND LangCode=LANGCODE;
END IF;
END;
I would have used a cursor but unlike Oracle, I couldn't find an example in HANA as to how to call one SQL or another plus that seems to be Dynamic SQL which HANA forbids in functions (but the above is allowed).
My issue with the above is that when I execute it in our GUI, it executes in ODBC not in a SQL console, and the warning becomes an error message:
E675217410:ODBC reported error.:[SAP AG][LIBODBCHDB SO][HDBODBC] General error; > 1347 Not recommended feature: Using SELECT INTO in Scalar UDF
Really there are two elements to this that I need:
the ability to have a slightly different query in HANA when the value TASKID is null or not null (i.e. if it's null, it's not part of the WHERE clause), and
that the query return the passed in default if no results are found.
Is there a way to get this to run in an ODBC call?
Thanks in advance
Do not use dynamic SQL until there's no really dynamic identifiers or dynamic code.
You write this query one time, but then such dynamic SQL will waste resources with every execution, so it is worth to invest more development time to have a single or copied static SQL.
What about answers:
Your statement can be reduced to single statement with ... and ( (:taskid is not null and Key3=:taskid) or :taskid is null) and no dynamic SQL. If you really need to have a dynamic SQL to return something, then you are limited to only scalar output for HANA 2.0 and no parameter binding at all (neither in, nor out) for HANA 1.0 (do not know if this works fine in 2.0).
This can be achieved with aggregation function on your value since aggregation function always return a value (null if no rows were passed where clause), If you want to have a single value with TOP (maybe you need a first row in some order), then you can wrap it into a subquery and then do a dummy aggregation on one row.
SELECT coalesce(max(Value), 'Your default value')
INTO SQLResults
FROM WML
WHERE ...
Or you may use exception handlers, but they are too bulky and with some not visually obvious error codes.
do begin
declare lv_str varchar(100);
begin
DECLARE EXIT HANDLER FOR SQL_ERROR_CODE 1299 /*no data found*/
lv_str := 'Default value';
select 10
into lv_str
from dummy
where 1 = 0;
end;
select :lv_str as res from dummy;
end;
| | RES |
+---+---------------+
| 1 | Default value |
What about the code: it is better to use colon in front of the variable not to mix it with table columns: if you'll have a typo, your query will evaluate, for example, LangCode=LANGCODE as always true for non-nulls and make the debug process hard.

SQL Server stored procedure: how to return column names/values of type failures in variable?

Ambiguous thread name, I apologize. I am not new to SQL, but I'm new to coding longer stored procedures so I don't deal with variables much outside of passing through maybe a table name or returning row count, etc.
I have a stored procedure that is executing an insert from a staging table to a fact table. There are a couple type casts in the insert.
If the insert fails due to a typecast. Is there any way to return the name of the column that failed, along with what the failed value was? How would I code that? I know that Try_parse would make it so the stored procedure doesn't fail on type cast failure, but I want to be able to pass back exactly what column and value failed.
I show an example here:
Create Procedure dbo.Example_Insert
#updateUser varchar(255)
As
Begin
Insert Into dbo.Energy_Costs (Energy_Cost_Id, Project_Id, Propane_Cost_Dollars,
Electricity_Cost_Dollars, Fuel_Savings_Evaluator)
Select
Next Value For energy_cost_id,
r.project_id,
Cast(r.propane_cost_dollars As Decimal(18,2)),
Cast(r.electricity_cost_dollars As Decimal(18,2)),
#update_user fuel_savings_evaluator
From
staging_table r
return ##ROWCOUNT
end
You can use CURSOR in sql then insert one line at a time. When insert fail return value currently row error.
I hope my idea suitable with you.

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).

Using User Defined Functions For A Specific Database in 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 ...

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.