Adapt T-SQL code to PL/SQL code - tsql

I just have a problem to convert some T-SQL code into PL/SQL.
This is the original part of code :
SET #ISOweek= DATEPART(wk,#DATE)+1
-DATEPART(wk,CAST(DATEPART(yy,#DATE) as CHAR(4))+'0104')
And after many research, i modify like that :
SET #ISOweek = TO_NUMBER(TRUNC(#DATE, 'IW')) + 1
- TO_NUMBER(TRUNC( (TO_CHAR(TRUNC(#DATE, 'YYYY'))) + '0104', 'IW'))
I can't test my code, that's why i come here for obtain your help. Can you say me if it's correct, or not? And what i've to modify because i'm a lost...
I read a lot of articles on this website, always helpfull.
Thank's for your answers
Cordialy,
Guillaume
The first problem it's ok, i've got a lot of responses and thnak's ;).
But i've another problem :
My T-SQL script :
USE [myBD ]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create function [Entity].[LPAD]
(
#pad_value varchar(500),
#pad_length int,
#pad_with varchar(10) = ' '
)
returns varchar(5000)
as
BEGIN
return ( replace(str(#pad_value,#pad_length),' ',#pad_with) )
END
GO
And i convert it in PL/SQL :
create OR REPLACE FUNCTION myBDOrcl.LPAD
(
pad_value varchar2,
pad_length number,
pad_with varchar2 := ' '
)
return varchar2
is retour varchar2(5000);
BEGIN
retour := replace(TO_CHAR(pad_length, pad_value ), ' ', pad_with);
return retour;
END;
I play the script and it's ok. BUT, i don't know how can I modify my variables : pad_value_varchar2 and the others, to specify the size...
I want to place a declare block, but it's not working....
Thank's for help guys

Related

Firebird dynamic Var New and Old

I need validate dynamic Fields from a Table. For example:
CREATE TRIGGER BU_TPROYECTOS FOR TPROYECTOS
BEFORE UPDATE AS
DECLARE VARIABLE vCAMPO VARCHAR(64);
BEGIN
/*In then table "TCAMPOS" are the fields to validate*/
for Select CAMPO from TCAMPOS where TABLA = TPROYECTOS and ACTUALIZA = 'V' into :vCAMPO do
Begin
if (New.:vCAMPO <> Old.:vCampo) then
/*How i get dynamic New.Field1, New.Field2 on query return*/
End;
END ;
The question is : How can I put "The name of the field that the query returns me " in the above code .
Ie if the query returns me the field1 and field5 , I would put the trigger
if ( New.Field1 < > Old.Field1 ) or ( New.Field5 < > Old.Field5 ) then
There is no such feature in Firebird. You will need to create (and preferably) generate triggers that will reference all fields hard coded. If the underlying table changes or the requirements for validation, you will need to recreate the trigger to take the added or removed fields into account.

Getting a value from stored procedure within a stored procedure

I have a stored procedure which returns an XML file. At the moment some calculations are done in XSL but I would like to do these within the database using another stored procedure. (adding the result of that calculation to the XML)
ALTER PROCEDURE [dbo].[app_Get_Phone_And_Tariffs]
-- Add the parameters for the stored procedure here
#phone nvarchar(150)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT
PB.UID as '#phoneid',
PB.Short_Title as '#title',
PB.Description as '#desc',
PB.Camera as '#camera',
PB.Storage as '#storage',
PB.Screen_Size as '#screensize',
PB.OS as '#os',
PB.Processor as '#chip',
PB.Image1 as '#image',
PB.Trade_Price as '#tradeprice',
(SELECT
TB.UID as '#tariffid',
TB.Tariff_Name as '#name',
TB.Carrier as '#network',
TB.Inclusive_Minutes as '#mins',
TB.Inclusive_Texts as '#texts',
TB.Inclusive_Data as '#data',
TB.Monthly_Cost as '#monthly',
TB.Commission as '#comm',
(TB.Commission - PB.Trade_Price) as '#upfront'
FROM dbo.Tariff_Base TB
WHERE TB.Active = 1 AND TB.Type = 1
FOR XML PATH('tariff'), TYPE
),
(SELECT
OP.GP_Margin as '#gpmargin'
FROM dbo.Options OP
FOR XML PATH('options'), TYPE
)
FROM dbo.Phone_Base PB
WHERE PB.Friendly_URL_Name = #phone AND PB.Active = 1
FOR XML PATH('detail'), TYPE
END
What I want to do is:
In the inner select (TB) is to call another SP lets call it "calculate" passing 2 variables (TB.Commission and PB.Trade_Price) for the sum
Calculate will return a value i.e. #hp to the stored procedure which can be added/used in the XML List.
Can this be done in SQL Server 2014/T-SQL?
No. But you could do it with a function. See the MSDN documentation, especially example A.
Something like this (untested):
CREATE FUNCTION dbo.Calculate (#Comission float, #TradePrice float)
RETURNS float
WITH EXECUTE AS CALLER
AS
BEGIN
DECLARE #SumVal float;
SET #SumVal = #Commission + # TradeValue;
RETURN(#SumVal);
END;
GO
--In your sub-query
SELECT values, dbo.Calculate(TB.Commission, PB.Trade_Price) AS A_Sum
FROM ...;

Trying to format INT in Money, but getting error: FORMAT is not a recognized built-in function

I'm trying to format the amount such as sums like 1588000 look like $1,588,000.
I've tried:
CASE
WHEN nb.AmountDollars IS NOT NULL THEN
CAST(FORMAT(nb.AmountDollars, '##,##0') AS VARCHAR(50))
ELSE ''
END
But I'm getting an error: 'FORMAT' is not a recognized built-in function name.
Yet I see many answers in stackoverflow people using FORMAT.
Thanks for helping
Here's a quick and dirty scalar function to split up the value for you.
CREATE FUNCTION [dbo].[fn_FormatDollars]
(
#RawValue INT
)
RETURNS VARCHAR(20)
AS
BEGIN
DECLARE #FormattedValue VARCHAR(20)
IF LEN(#RawValue) > 6
BEGIN
SELECT
#FormattedValue = '$' +
LEFT(CAST(#RawValue AS VARCHAR),1) + ',' +
SUBSTRING(CAST(#RawValue AS VARCHAR),2,3) + ',' +
RIGHT(CAST(#RawValue AS VARCHAR),3)
END
ELSE
BEGIN
SELECT
#FormattedValue ='$' +
SUBSTRING(CAST(#RawValue AS VARCHAR),1,3) + ',' +
RIGHT(CAST(#RawValue AS VARCHAR),3)
END
RETURN #FormattedValue
END
GO
Then use it like this with your field:
SELECT [dbo].[fn_FormatDollars](nb.[AmountDollars])
Example:
SELECT [dbo].[fn_FormatDollars](1588000)
Result:
I wrote this against a SQL 2005 instance just to play save.

Using patterns in REPLACE

I need to find and replace an expression within a dynamic query. I have a subset of a where condition in string type like
'fieldA=23 OR field_1=300 OR fieldB=4'
What I need is to find a way to detect expression field_1=300 within the string and replace it while retaining the expression field_1=300.
I can do the detection part using CHARINDEX or PATINDEX but I'm not able to figure out how to use the patterns in the REPLACE function and how to get the value of the field_1 parameter.
Thanks in advance.
I'm not entirely clear on what you're trying to acheieve (e.g. what are you wanting to replace "field_1=300" with, and is it the exact string "field_1=300" that you're looking for, or just the field name, i.e. "field_1"?).
Also, could you paste in the code you've written so far?
Here's a simple script which will extract the current value of a given field name:
DECLARE #str VARCHAR(100),
#str_tmp VARCHAR(100),
#field_pattern VARCHAR(10),
#field_val INT;
SET #str = 'fieldA=23 OR field_1=300 OR fieldB=4';
SET #field_pattern = 'field_1='
-- This part will extract the current value assigned to the "#field_pattern" field
IF CHARINDEX(#field_pattern, #str) > 0
BEGIN
SELECT #str_tmp = SUBSTRING(#str,
CHARINDEX(#field_pattern, #str) + LEN(#field_pattern),
LEN(#str)
);
SELECT #field_val = CAST(SUBSTRING(#str_tmp, 1, CHARINDEX(' ', #str_tmp)-1) AS INT);
END
PRINT #field_val
If you want to replace the value itself (e.g. replacing "300" in this case with "600"), then you could add something like this:
DECLARE #new_val INT;
SET #new_val = 600;
SET #str = REPLACE(#str, (#field_pattern+CAST(#field_val AS VARCHAR)), (#field_pattern+CAST(#new_val AS VARCHAR)));
PRINT #str;
Which would give you "fieldA=23 OR field_1=600 OR fieldB=4".
Cheers,
Dave

Data tweaking code runs fine when executed directly - but never stops when used in trigger

I have written some code to ensure that items on an order are all numbered (the "position number" or "item number" has been introduced only recently and we did not want to go and change all related code - as it is "asthetics only" and has no functional impact.)
So, the idea is to go and check for an records that jave an itemno of NULL or 0 - and then compute one and assign it. When executing this code in a query window, it works fine. When putting it into an AFTER INSERT-trigger, it loops forever.
So what is wrong here?
/****** Objekt: Trigger [SetzePosNr] Skriptdatum: 02/28/2010 20:06:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [SetzePosNr]
ON [dbo].[bestellpos]
AFTER INSERT
AS
BEGIN
DECLARE #idb int
DECLARE #idp int
DECLARE #pnr int
SELECT #idp=id,#idb=id_bestellungen FROM bestellpos WHERE posnr IS NULL OR posnr=0
WHILE #idp IS NOT NULL
BEGIN
SELECT #pnr = 1+max(posnr) FROM bestellpos WHERE id_bestellungen = #idb
print( 'idp=' + str(#idp) + ', idb=' + str(#idb) + ', posnr=' + str(#pnr))
UPDATE bestellpos SET posnr=#pnr WHERE id=#idp
SELECT #idp=id,#idb=id_bestellungen FROM bestellpos WHERE posnr IS NULL OR posnr=0
END
END
Aaaargh - just found the problem: the 3d line (from the end, the SELECT-statement) does not assign the variables when there result of the WHERE is NULL. So "set #idp=null" before that statement has fixed the problem!
Not sure whhy I assumed a problem between direct execution and triggering of these statements, seems I picked the wrong test-cases :(