subquery in FROM must have an alias for sql query - sql

I have this code snippet for a query below.
"SELECT DISTINCT(CODE) FROM (" +
"SELECT TRIM(BOTH ' ' FROM PROJECT_NUMBER) CODE FROM SCHEMA.TABLE_NAME " +
"WHERE PROJECT_NUMBER IS NOT NULL " +
"AND LAST_UPDATE_DATE >= :lastUpdateDate " +
"UNION " +
"SELECT TRIM(BOTH ' ' FROM ANOTHER_CODE) CODE FROM SCHEMA.TABLE_NAME " +
"WHERE ANOTHER_CODE IS NOT NULL " +
"AND LAST_UPDATE_DATE >= :lastUpdateDate " +
") " +
"WHERE CODE IS NOT NULL";
I'm in the process of migrating to postgres from oracle and I'm seeing these errors in our logs:
Caused by: org.postgresql.util.PSQLException: ERROR: subquery in FROM must have an alias
Hint: For example, FROM (SELECT ...) [AS] foo.
Where should the alias go, do I need for all subqueries, and do I need to use the alias in this query? Little confused here.

"SELECT DISTINCT(CODE) FROM (" +
"SELECT TRIM(BOTH ' ' FROM PROJECT_NUMBER) CODE FROM SCHEMA.TABLE_NAME " +
"WHERE PROJECT_NUMBER IS NOT NULL " +
"AND LAST_UPDATE_DATE >= :lastUpdateDate " +
"UNION " +
"SELECT TRIM(BOTH ' ' FROM ANOTHER_CODE) CODE FROM SCHEMA.TABLE_NAME " +
"WHERE ANOTHER_CODE IS NOT NULL " +
"AND LAST_UPDATE_DATE >= :lastUpdateDate " +
") as qry " +
"WHERE CODE IS NOT NULL";

Related

SQL cmd.command include an OR statement

Below is my SQL cmd.CommandText query:
cmd.CommandText = "SELECT CONVERT(date, [DateTime]) 'Date of Download', ActionBy AS 'User Full Name', COUNT(DISTINCT CAST(Identifier AS NVARCHAR(10)) + Remarks + Link) 'Number of Document Downloads' " +
" FROM [dbo].[AuditLog] "+
" WHERE ActionTaken = 'Clicked' "+
" and Type = 'Attachment Link'" +
" and CONVERT(date, [DateTime]) BETWEEN CONVERT(date,'" + scanStartDate.ToString("yyyy-MM-dd HH:mm:ss.fff") + "') and CONVERT(date,'" + scanEndDate.ToString("yyyy-MM-dd HH:mm:ss.fff") + "') "+
" GROUP BY CONVERT(date, [DateTime]), ActionBy "+
" HAVING COUNT(DISTINCT Identifier) > " + limit +
" ORDER BY COUNT(DISTINCT Identifier) DESC";
I would like to include an extra parameter OR for Type, like as follows:
" and Type = 'Attachment Link' OR 'Attachment Link - Search'" +
May I know how can it be done?
Thank you.
Edit: Apologies, did not add in the error message, as follow.
An expression of non-boolean type specified in a context where a condition is expected, near 'and'.
specify the column after your OR operator
cmd.CommandText = "SELECT CONVERT(date, [DateTime]) 'Date of Download', ActionBy AS 'User Full Name', COUNT(DISTINCT CAST(Identifier AS NVARCHAR(10)) + Remarks + Link) 'Number of Document Downloads' " +
" FROM [dbo].[AuditLog] "+
" WHERE ActionTaken = 'Clicked' "+
" and (Type = 'Attachment Link' OR Type = 'Attachment Link - Search') " +
" and CONVERT(date, [DateTime]) BETWEEN CONVERT(date,'" + scanStartDate.ToString("yyyy-MM-dd HH:mm:ss.fff") + "') and CONVERT(date,'" + scanEndDate.ToString("yyyy-MM-dd HH:mm:ss.fff") + "') "+
" GROUP BY CONVERT(date, [DateTime]), ActionBy "+
" HAVING COUNT(DISTINCT Identifier) > " + limit +
" ORDER BY COUNT(DISTINCT Identifier) DESC";
I assume I am over-simplifying but do you mean:
cmd.CommandText = "SELECT CONVERT(date, [DateTime]) 'Date of Download', ActionBy AS 'User Full Name', COUNT(DISTINCT CAST(Identifier AS NVARCHAR(10)) + Remarks + Link) 'Number of Document Downloads' " +
" FROM [dbo].[AuditLog] "+
" WHERE ActionTaken = 'Clicked' "+
" and (Type = 'Attachment Link' OR Type = 'Attachment Link - Search') " +
" and CONVERT(date, [DateTime]) BETWEEN CONVERT(date,'" + scanStartDate.ToString("yyyy-MM-dd HH:mm:ss.fff") + "') and CONVERT(date,'" + scanEndDate.ToString("yyyy-MM-dd HH:mm:ss.fff") + "') "+
" GROUP BY CONVERT(date, [DateTime]), ActionBy "+
" HAVING COUNT(DISTINCT Identifier) > " + limit +
" ORDER BY COUNT(DISTINCT Identifier) DESC";
You might need ( ) for order of operations and I think you mean "=" instead of "-".

IF NOT EXISTS in UCanAccess

I have the following code, but UCanAccess does not allow me to use IF NOT EXISTS. Does anyone have any ideas?
"if not exists (select ArtikelNr from Artikel where ArtikelNr='"+ValueRead.prüfen1()+"')" +
"begin" +
" if not exists (select isa_id from Artikel where isa_id='"+Integer.parseInt(Data.textField.getText())+"')" +
" begin" +
"INSERT INTO Artikel ([HERE ARE THE TABLES) VALUES
[HERE ARE THE VALUES]
" end" +
"end";
You could do something like this:
// test data
int artikelNr = 123;
int isa_id = 1234;
String description = "artikel_123";
String sql = ""
+ "INSERT INTO Artikel (ArtikelNr, isa_id, description) "
+ "SELECT ? AS ArtikelNr, ? AS isa_id, ? as description "
+ "FROM DUAL "
+ "WHERE NOT EXISTS ("
+ " SELECT * FROM Artikel "
+ " WHERE ArtikelNr=? AND isa_id=?)";
PreparedStatement ps = conn.prepareStatement(sql);
// values to INSERT
ps.setInt(1, artikelNr);
ps.setInt(2, isa_id);
ps.setString(3, description);
// values for WHERE NOT EXISTS
ps.setInt(4, artikelNr);
ps.setInt(5, isa_id);
int rtn = ps.executeUpdate();
System.out.printf("%d row(s) inserted%n", rtn);

Can these two SQL statements be made into one? Changing multiple indices with two constraints

I have a form that users can use to edit data in my database. The database is structured like this:
If a user wants to edit both a FAVE_COLOR and a FAVE_FOOD, how would I go about doing that in my SQL statement? I can think of this, but is there a way to do this in one statement?
string sql1 = "UPDATE MYTABLE " +
"SET PROP_VALUE = '" + form["color"] + "' " +
"WHERE ID = " + form["id"] + " " +
"AND PROP_NAME = 'FAVE_COLOR'"
string sql2 = "UPDATE MYTABLE " +
"SET PROP_VALUE = '" + form["food"] + "' " +
"WHERE ID = " + form["id"] + " " +
"AND PROP_NAME = 'FAVE_FOOD'"
string sql = "UPDATE MYTABLE " +
"SET PROP_VALUE = CASE " +
"WHEN PROP_NAME = 'FAVE_COLOR' THEN '" + form["color"] + "' " +
"WHEN PROP_NAME = 'FAVE_FOOD' THEN '" + form["food"] + "' " +
"END " +
"WHERE ID = " + form["id"] + " " +
"AND PROP_NAME IN ('FAVE_COLOR', 'FAVE_FOOD')"
But beware of SQL injection! You really should be using prepared statements, into which you pass your variables as parameters that do not get evaluated for SQL. If you don't know what I'm talking about, or how to fix it, read the story of Bobby Tables.
You can use case statements:
UPDATE MYTABLE
SET PROP_VALUE = (
CASE favefood
WHEN PROP_NAME = 'FAVE_FOOD'
THEN 'PIZZA'
CASE favecolor
WHEN PROP_NAME = 'FAVE_COLOR'
THEN 'BLUE'
WHERE ID = #myIdValue
For MS SQL Server you can use an UPDATE FROM which will update two properties at the same time, like this:
CREATE TABLE MYTABLE (
ID INT,
PROP_NAME VARCHAR(20),
PROP_VALUE VARCHAR(20));
go
INSERT INTO MYTABLE VALUES (1, 'A','B')
go
INSERT INTO MYTABLE VALUES (1, 'C', 'D')
go
UPDATE MYTABLE
SET PROP_VALUE = X.PROP_VALUE
FROM MYTABLE MT JOIN (
SELECT 'A' AS PROP_NAME, 'F' AS PROP_VALUE
UNION
SELECT 'C' AS PROP_NAME, 'G' AS PROP_VALUE) AS X ON MT.PROP_NAME = X.PROP_NAME
WHERE ID = 1
For other SQL DB server the solution should be similar if not identical.

SQL UPDATE doesn't work with foreign languages (Arabic)

the UPDATE gives ???? if the updater field was written in Arabic and this is my query:
UPDATE students
SET first_name = 'الاسم' , last_name = 'الاسم الاخير' ,
father_name = 'الاسم الاخير' , mother_name = '',
birth_date = '1/1/1990 12:00:00 AM' , education_level = '' ,
address = '' , notes = ''
WHERE student_id = 33
And here is the result of the update:
student_id first_name last_name mother_name father_name birth_date
33 ????? ????? ?????? ??????????? 1990-01-01
//the answer is great and thank you people, another question is that I am using this UPDATE syntax in my C# program
command.CommandText = "UPDATE students SET " +
"first_name = " + "'" + first_name + "'" + " , last_name = " + "'" + last_name + "'" +
" , father_name = " + "'" + father_name + "'" + " , mother_name = " +
"'" + mother_name + "'" + ", birth_date = " + "'" + birth_date + "'" +
" , education_level = " + "'" + education_level + "'" +
" , address = " + "'" + address + "'" + " , notes = " + "'" + notes + "'" +
" WHERE student_id = " + id ;
//how to use the character N
You have forgotten the N prefix before your string literals which is required so they will be treated as nvarchar rather than varchar
SET first_name = N'الاسم' etc.
without that the text is coerced into whatever characters the code page of your default collation can deal with.
Create the database with this collation Arabic_CI_AS, you won't need to put N before the Arabic characters.

How to fetch distinct values from multiple rows of select query?

I have used query as
string getPlayers = " Select Player1,Player2,Player3,Player4,Player5 from tbl_game where Player1=" + userid + " OR Player2=" + userid + " OR Player3=" + userid + " OR Player4=" + userid + " OR Player5=" + userid + " AND Complete = 'No' ";
It gives result as multiple rows that fulfills the condition.
But I want to store values of distinct Player1,Player2,Player3,Player4,Player5 in variables returned from select query, so that i can use these values for further case.
How can i do this ?
Please help me. I am very confused.
EDITED :
I got the result of select query as -
(1,2,2,4,5)
(2,3,1,4,5)
(4,3,5,1,2)
Where 1,2,3,4,5 are userids(players).
I want store these userids in variables as -
p1=1 , p2=2 , p3=3 ,p4=4, p5=5
string getPlayer1 = (" select var1 from (" Select distinct Player1 as var1 ,Player2,Player3,Player4,Player5 from tbl_game where Player1=" + userid + " OR Player2=" + userid + " OR Player3=" + userid + " OR Player4=" + userid + " OR Player5=" + userid + " AND Complete = 'No' "));
var1 will have a value of player1. Repeat this for all other players. Hope this is what you want.