How to make the query work in linux server? - linux

I have an database in PostgreSQL called "myDatabase" which has hundreds of schema and which is installed in Linux server. I am using this DB for an SAAS application. Which has multiple schema users. I want to update a column value in a table for selected schema
There is a particular column 'Percentage' in a table called 'sales' which i want to update the column value for all the existing users(Schema). So i have written a script to update the values in all schemas, this script is working in windows server but when i trying to execute this script in linux server, it shows an error
enter code hereThe below script i have written,
DO
$do$
DECLARE
_schema text;
BEGIN
FOR _schema IN
SELECT quote_ident(nspname) -- prevent SQL injection
FROM pg_namespace n
WHERE nspname !~~ 'pg_%' and nspname between 'schema1' and 'schema50'
AND nspname <> 'information_schema'
LOOP
EXECUTE 'SET LOCAL search_path = ' || _schema;
UPDATE sales SET sales.Percentage = 15;
END LOOP;
END
$do$
The above script is working in windows server but it is not working linux server. The error is given below
ERROR: column "sales" of relation "sales" does not exist
LINE 1: UPDATE sales SET sales.Percentage = 5
^
QUERY: UPDATE sales SET sales.Percentage = 5
CONTEXT: PL/pgSQL function inline_code_block line 10 at SQL statement
SQL state: 42703
Any help will be appreciated

Do not specify table name before the column name in the update:
UPDATE sales SET Percentage = 15
Here is the example that demonstrates this:
laika=# create table a (i integer);
CREATE TABLE
laika=# update a set a.i = 1;
ERROR: column "a" of relation "a" does not exist
LINE 1: update a set a.i = 1;
^
laika=# update a set i = 1;
UPDATE 0

Related

SQL Insert Update on tables with Select causing Locks and wait issue may using MERGE

We have two database tables : PointsMaster (PM) and PointsDetails (PD), the requirement here is to check if PM table has currentbalance of greater than "x" and if it is greater than "x" then update the PM table's currentbalance (i.e. reduce currentbalance by "x") and then also put a new record in the PD table about this "x" points.
If the currentbalance is lower than "x" then no updates to PM table and no insert to PD table.
If currentbalance is NULL then simply we need to return back null.
Right now writing these individual:- SELECT and then UPDATE (PM) and INSERT (PD) is causing lock issues and I am thinking of using "MERGE" (on PM Table) so I can do SELECT and UPDATE in one transaction and not cause any locks on PM table but my issue here is how do I check if CurrentBalance is Null or Lower than "X" and return that back so that processing can happen for those 2 conditions (i.e. of Null balance or when balance is less than "x").
MERGE can help me here with SELECT and if MATCHED UPDATE on PM.. but the INSERT on PD has to happen only if UPDATE on PM happened else not and also if Balance is lower than "x" or Null I have to return that back and not UPDATE PM or ADD record to PD.
Any help here? As the code we have is causing locks and waits and is not efficient with volume of data. PM and PD tables have required indexes in place.
All of the above is being done from C#.Net in a Azure hosted Function App.
Thinking of following SQL Code
Declare #rcount INT;
MERGE PointsMaster as tgt
Using PointsMaster as src
ON (tgt.ProfileID = src.ProfileID)
WHEN MATCHED AND tgt.ProfileID ='3589153' and tgt.CurrentBalance > 50000000
Then UPDATE SET tgt.CurrentBalance = tgt.CurrentBalance - 5;
Set #rcount= ##ROWCOUNT;
if (#rcount > 0)
Begin
INSERT INTO PointsDetails ( PointsHeaderID,Debit,Credit,ActionTypeCode,TransactionDate) Values (3587854,5,0,'AT2',Getdate())
End
if (#rcount = 0)
Begin
SELECT * from PointsMaster where ProfileID = '3589153'
End

Update SQLite row with certain number

I have a problem that I can't solve with better-sqlite3 on node.js
I have a table looking somewhat like this:
image of table
How can I change each rows xp, that has a level of 3 to 100? So in this example it should change id's 1 and 4 xp value to 100.
Any help is appreciated!
This is a pretty basic SQL Query, you're just needing to do a WHERE on all levels that equal 3.
UPDATE tableName
SET level = 100
WHERE level = 3
Looking at the better-sqlite3 documentation, to do an UPDATE you simply need to call the function using run()
const stmt = db.prepare('UPDATE tableName SET level = ? WHERE level = ?');
const info = stmt.run(3, 100);

SQL trigger with parameter

I have a nodejs app with SQL Server. I want to be able to update a table for a "specific org" based on an insert and delete action. Let's say I have 2 tables as follows:
Project: projId, orgId, projName
Tasks: taskId, projId, taskName
Users: userId, orgId, userName
OrganizationStats: numberOfProjects, numberOfUsers, numberOfTasks orgId
So let's say I add a new project for an organization where orgId = 1. My insert statement from Nodejs would be:
insert into project (projId, orgId, projName)
values (${'projId'}, ${'orgId'}, 'New Project');
I want to write a trigger in SQL Server that adds 1 to the numberOfProjects column with orgId that's passed in.
create trigger updateProjectAfterInsert
on project
after insert
as
begin
update OrganizationStats
set numprojects = numberOfProjects + 1
where orgId = 'THE_INSERTED_ORGID_VALUE';
end;
My problem is I don't know how to pass the ${'orgId'} to the trigger.
I'm going to expand on my comment here:
Personally, I recommend against storing values which can be calculated by an aggregate. If you need such information easily accessible, you're better off making a VIEW with the value in there, in my opinion.
What I mean by this is that NumProjects has "no right" being in the table OrganizationStats, instead it should be calculated at the time the information is needed. You can't use an aggregate function in a computed column's definition without a scalar function, and those can be quite slow. Instead I recommend creating a VIEW (or if you prefer table value function) to give you the information from the table:
CREATE VIEW dbo.vw_OrganisationStats AS
SELECT {Columns from OrganizationStats},
P.Projects AS NumProjects
FROM dbo.OrganizationStats OS
CROSS APPLY (SELECT COUNT(*) AS Projects
FROM dbo.Projects P
WHERE P.OrgID = OS.OrgID) P;
I use a CROSS APPLY with a subquery, as then you don't need a huge GROUP BY at the end.
I think what you want this something like this:
CREATE TRIGGER updateProjectAfterInsert
ON Project
AFTER INSERT
AS
BEGIN
UPDATE OrganizationStats
SET NumProjects = NumProjects + 1
WHERE OrgId IN (SELECT OrgId FROM inserted);
END;
Also note, Triggers must always assume multiple rows. It's possible to insert multiple rows, update multiple rows, and delete multiple rows. The "inserted" and "deleted" collections contain the data needed ("inserted" contains the rows being inserted, "deleted" contains the rows being deleted, and on an update "inserted" contains the values after the update, and "deleted" contains the values before the update).

Kentico Repeater with Custom Query

OK Here we go.
Using Kentico 11/Portal Engine (no hot fixes)
Have a table that holds Content only page Types. One field of importance is a Date and time field.
I am trying to get rows out of this table that match a certain month and year criteria. For instance give me all records where Month=2 and Year=2018. These argument will be passed via the query string
I have a custom Stored proc that I would like to receive two int(or string) arguments then return a collection of all matching rows.
I am using a RepeaterWithCustomQuery to call the procedure and handle the resulting rows. As you can see below the querystring arguments are named "year" and "monthnumber".
The Query
Me.PR.PREDetailSelect
When my Webpart is set up in this configuration I get the following error:
In my Query, I have tried:
EXEC Proc_Custom_PRDetails #MonthNumber = ##ORDERBY##; #Year = ##WHERE##<br/>
EXEC Proc_Custom_PRDetails #MonthNumber = ##ORDERBY##, #Year = ##WHERE##<br/>
EXEC Proc_Custom_PRDetails #MonthNumber = ##ORDERBY## #Year = ##WHERE##<br/>
Any help would be appreciated (Thanks in advance Brendan). Lastly, don't get too caught up in the names of specific objects as I tried to change names to protect the innocent.
Those macros for queries are not meant to be used with stor procs. The system generates this false condition 1=1 in case if you don't pass anything so it won't break the sql statement like the one below:
SELECT ##TOPN## ##COLUMNS##
FROM View_CMS_Tree_Joined AS V
INNER JOIN CONTENT_MenuItem AS C
ON V.DocumentForeignKeyValue = C.MenuItemID AND V.ClassName = N'CMS.MenuItem'
WHERE ##WHERE##
ORDER BY ##ORDERBY##
You need to convert you stor proc to SQL statement then you can use these SQL macros or use stor proc without parameters
If look at the query above top and where are not good because system will do adjustment, but you can use order by and columns, but they both must be present (I think it passes them as is):
exec proc_test ##ORDERBY##, ##COLUMNS##
Honestly I would advice against doing this, plus you won't gain much by calling stor proc.

Using rdb$get_context as default value for a column

In a Firebird database, I need to create a DOMAIN with default value taken from the context variable.
It should be something like
CREATE DOMAIN USER_ID AS INTEGER
DEFAULT RDB$GET_CONTEXT('USER_SESSION','UID') NOT NULL;
When I execute this, I am getting the following error
Invalid token.
Dynamic SQL Error.
SQL error code = -104.
Token unknown - line 2, column 13.
RDB$GET_CONTEXT.
How can this be done, maybe there is another way than the DEFAULT clause?
Just create a BEFORE INSERT trigger:
CREATE TRIGGER your_trigger_name FOR your_table
BEFORE INSERT
POSITION 0
AS
BEGIN
IF (NEW.your_field IS NULL) THEN
NEW.your_field = RDB$GET_CONTEXT('USER_SESSION','UID');
END

Resources