SQL select works in Management Studio, but not from website - sql-server

I have the following query:
SELECT
[tblstudentrakazot].studentid, firstname, lastname, tblRakezetSchedule.*
FROM
tblRakezetSchedule
INNER JOIN
[tblstudentrakazot] ON [tblstudentrakazot].scheduleID = tblRakezetSchedule.scheduleid
INNER JOIN
tblstudents ON [tblstudentrakazot].studentid = tblstudents.studentid
WHERE
scheduleday = datepart(w,convert(datetime,'21/2/2016',103))
AND tblRakezetSchedule.rakezetID = 182
ORDER BY
replace(scheduletimefrom, ':', '')
When run from SQL Server Management Studio, it works perfectly and generates 3 records.
When run from my VBscript app, I get no records
The issue seems to be in the filter that refers to the date scheduleday = datepart(w,convert(datetime,'21/2/2016',103)) - when I comment that out, the query works.
Does anyone know what the issue can be?
I have tried playing with the date settings but that didnt change anything.
I have tried doing CONVERT(int,scheduleday) in the WHERE - that didn't help either, as the scheduleday is already a number format field.
I have tried using dw in the datepart instead of w - also no change.
Thanks in advance
UPDATE:
The query works when I do WHERE CONVERT(int,scheduleday) = 1
Also - I see that CONVERT(int,datepart(w,convert(datetime,'21/02/2016',103))) correctly gives 1 too. Its just weird that 1 <> 1 even when they are both converted to INT
Here is my VBscript:
sql = "SELECT [tblstudentrakazot].studentid, firstname, lastname, tblRakezetSchedule.* FROM tblRakezetSchedule"
sql = sql & " INNER join [tblstudentrakazot] on [tblstudentrakazot].scheduleID = tblRakezetSchedule.scheduleid "
sql = sql & " INNER join tblstudents on [tblstudentrakazot].studentid = tblstudents.studentid"
sql = sql & " WHERE "
sql = sql & " CONVERT(int,scheduleday) = datepart(w,convert(datetime,'" & cleanSQL(planneddate) & "',103)) AND "
sql = sql & " tblRakezetSchedule.rakezetID = " & CleanSQL(x_rakezetID)
sql = sql & " ORDER BY replace(scheduletimefrom, ':', '')"
WHERE:
x_rakezetID = 182
and planneddate is a date variable in the format of `21/02/2016'

The result of SELECT datepart(w,convert(datetime,'21/2/2016',103)) will depend on your session's language settings (which will depend on the user.) For example:
SET LANGUAGE German;
SELECT datepart(w,convert(datetime,'21/2/2016',103)) ;
...returns 7, whereas for English it returns 1.
I therefore suspect that you are using different users or at least different language settings when connection through SSMS versus through your application.

Related

Crystal Reports XI - syntax error in query working ok in SQL Server

I have a query, and in SQL Server Management Studio (2008), it is working perfectly, but when I add a subreport to my report when the same query with dynamic params, I get two errors.
The first time the values that I set in the set default values like, for example 'A' is interpreted like a column name and showing
Invalid column name A
When I send a constant 'A' without parameter, no errors are shown.
This is my code:
select top 1
isnull( dtssegcabv.dscv_fecharecepcion, 0) as FechaRecepcion
from
CabVenta
join
dtssegcabv on CabVenta.cvescv_id = dtssegcabv.scv_id
where
CabVenta.cve_letra = {?cve_letra}
and CabVenta.cve_codpvt = {?cve_codpvt}
and CabVenta.cve_nro = {?cve_nro}
and CabVenta.cvetco_cod = {?cvetco_cod}
If I send no default values (let the dialog empty), the error is
Incorrect Syntax Near Keyword And
I repeat, the query in SQL Server is working fine. The datatypes are all varchar.
Thanks for your help and sorry for my bad English.
It was a quotes problem:
select top 1
isnull( dtssegcabv.dscv_fecharecepcion, 0) as FechaRecepcion
from
CabVenta
join
dtssegcabv on CabVenta.cvescv_id = dtssegcabv.scv_id
where
CabVenta.cve_letra = '{?cve_letra}'
and CabVenta.cve_codpvt = '{?cve_codpvt}'
and CabVenta.cve_nro = '{?cve_nro}'
and CabVenta.cvetco_cod = '{?cvetco_cod}'
Works Perfectly

"Relation does not exist" error, only with libpq

I'm trying to run this query to insert new row to Users table from my C code using PQexec() (libpq)
INSERT INTO Users
VALUES ((
SELECT MIN(s.id)
FROM generate_series(1,(
SELECT GREATEST(MAX(Id) + 1,1) FROM Users
)) AS s(id)
WHERE NOT EXISTS (SELECT 1 FROM Users WHERE Id = s.id))
, 'Tester', 27)
RETURNING Id;
It performs what i need when i run it in psql terminal, but from C it returns
Error executing query: ERROR: relation "users" does not exist
I checked connection status and it succeeded, using the same user i connect to from terminal. How come it can't find the users table?
EDIT: adding C-code
Connection:
sprintf(connect_param,"host=address dbname=%s user=%s password=%s",
USERNAME, USERNAME, PASSWORD);
conn = PQconnectdb(connect_param);
Query:
sprintf(cmd, "INSERT INTO Users "
"VALUES (( "
"SELECT MIN(s.id) "
"FROM generate_series(1,( "
"SELECT GREATEST(MAX(Id) + 1,1) FROM Users "
" )) AS s(id) "
"WHERE NOT EXISTS (SELECT 1 FROM Users WHERE Id = s.id)) "
" , \'%s\', %d) "
"RETURNING Id;", Name, Age);
res = PQexec(conn,cmd);
I am going for deduction:
Error executing query: ERROR: relation "users" does not exist
This kind of error is throw when the databases doesn't find the table(view, or wathelse can pass through a SELECT, he gives the name of "relation") .So your code looks fine, but a sub-set of reasons can be:
the table users doesn't exists. Some spelling mistake
you perform the query in the wrong database (where this table is not defined)
you perform the query in the wrong server (as above)
you perform the query in the wrong schema (as above)
The string get truncate from the sprintf.
and similar. The connection works very well since you get an answer from the database
your problem of library link to compilation.
gcc -I/usr/include/postgresql/ -L/usr/lib/postgresql/8.3/lib/ -lpq

Passing a SQL result to a 2nd SQL query

I'm coming to the end of setting up my first Python script which involves querying my SQL Server (which I've removed credentials for privacy reasons).
This is a excerpt of the code for which I can successfully login and query my SQL Server db.
I know my 2 SELECT queries work independently as I've tested already. But I've come unstuck setting the first SELECT query as a variable which I wish to pass into the 2nd Select queries where clause.
In SQL terms, I wish to set the adjusted date as the variable StartDate (from my first SELECT) and pass this to the Where statement in my 2nd SELECT statement. I think I'm failing on setting the variable properly. To reconfirm, I've verified the SELECT statements work from Python.
Is there something I need to add? Any suggestions appreciated.
import csv
import os
import urllib.request
import pymssql
conn = pymssql.connect(server='', user='', password='', database='')
StartDate = conn.cursor()
StartDate.execute('SELECT Dateadd(dd, -19, MAX(LastDateValue)) FROM tbl_Date')
ASXCodes = conn.cursor()
ASXCodes.execute('SELECT ASXCode FROM tbl_Company WHERE (ASX200 = 1 OR
MarketIndex =1 OR SegmentIndex = 1) AND Delisted = 0 AND LastTraded
>= StartDate ORDER BY ASXCode')
Just guessing - couldn't you do everything in one single query?
SELECT ASXCode FROM tbl_Company WHERE (ASX200 = 1 OR MarketIndex =1 OR SegmentIndex = 1) AND Delisted = 0 AND LastTraded >= (SELECT Dateadd(dd, -19, MAX(LastDateValue)) FROM tbl_Date) ORDER BY ASXCode
Also, I would imagine that tbl_Date.LastDateValue is indexed? If you get many records, that could be rather expensive...

Trouble with query in vb.net

I'm getting an error stating that say column doesnt belong to table. Here is my query below, its pretty straight forward.
query = " SELECT A.COLUMN "
" FROM TABLE_1 A, TABLE_2 B"
" WHERE A.COLUMN = B.COLUMN "
For simplicity sake, I put it into a dataset and do a for loop and it works fine. By the way tested query in management studio and it all works fine.
This is where have the problem:
dim new_val as string
new_val = row("A.COLUMN") 'ERROR
NOTE: When i change my query to :
SELECT A.COLUMN **AS COLUMN1**
and then:
new_val = row("COLUMN1") it works.
Does anyone know the reason for this?? Also forgot to note that some columns have the same name thats why i use A.COLUMN.
Just use:
new_val = row("COLUMN")
There is no reason to have the table suffix in your reference, just the column name.
Also, you really should re-write your query to use INNER JOINS:
query = " SELECT A.COLUMN "
" FROM TABLE_1 A INNER JOIN TABLE_2 B ON A.COLUMN = B.COLUMN "
I would suggest that you set the breakpoint in the problematic line and check the name of the column in the quick watch window. In this case, you will be able to determine the column name and thus adjust your code.

How to do Sql Server CE table update from another table

I have this sql:
UPDATE JOBMAKE SET WIP_STATUS='10sched1'
WHERE JBT_TYPE IN (SELECT JBT_TYPE FROM JOBVISIT WHERE JVST_ID = 21)
AND JOB_NUMBER IN (SELECT JOB_NUMBER FROM JOBVISIT WHERE JVST_ID = 21)
It works until I turn it into a parameterised query:
UPDATE JOBMAKE SET WIP_STATUS='10sched1'
WHERE JBT_TYPE IN (SELECT JBT_TYPE FROM JOBVISIT WHERE JVST_ID = #jvst_id)
AND JOB_NUMBER IN (SELECT JOB_NUMBER FROM JOBVISIT WHERE JVST_ID = #jvst_id)
Duplicated parameter names are not allowed. [ Parameter name = #jvst_id ]
I tried this (which i think would work in SQL SERVER 2005 - although I haven't tried it):
UPDATE JOBMAKE
SET WIP_STATUS='10sched1'
FROM JOBMAKE JM,JOBVISIT JV
WHERE JM.JOB_NUMBER = JV.JOB_NUMBER
AND JM.JBT_TYPE = JV.JBT_TYPE
AND JV.JVST_ID = 21
There was an error parsing the query. [ Token line number = 3,Token line offset = 1,Token in error = FROM ]
So, I can write dynamic sql instead of using parameters, or I can pass in 2 parameters with the same value, but does someone know how to do this a better way?
Colin
Your second attempt doesn't work because, based on the Books On-Line entry for UPDATE, SQL CE does't allow a FROM clause in an update statement.
I don't have SQL Compact Edition to test it on, but this might work:
UPDATE JOBMAKE
SET WIP_STATUS = '10sched1'
WHERE EXISTS (SELECT 1
FROM JOBVISIT AS JV
WHERE JV.JBT_TYPE = JOBMAKE.JBT_TYPE
AND JV.JOB_NUMBER = JOBMAKE.JOB_NUMBER
AND JV.JVST_ID = #jvst_id
)
It may be that you can alias JOBMAKE as JM to make the query slightly shorter.
EDIT
I'm not 100% sure of the limitations of SQL CE as they relate to the question raised in the comments (how to update a value in JOBMAKE using a value from JOBVISIT). Attempting to refer to the contents of the EXISTS clause in the outer query is unsupported in any SQL dialect I've come across, but there is another method you can try. This is untested but may work, since it looks like SQL CE supports correlated subqueries:
UPDATE JOBMAKE
SET WIP_STATUS = (SELECT JV.RES_CODE
FROM JOBVISIT AS JV
WHERE JV.JBT_TYPE = JOBMAKE.JBT_TYPE
AND JV.JOB_NUMBER = JOBMAKE.JOB_NUMBER
AND JV.JVST_ID = 20
)
There is a limitation, however. This query will fail if more than one row in JOBVISIT is retuned for each row in JOBMAKE.
If this doesn't work (or you cannot straightforwardly limit the inner query to a single row per outer row), it would be possible to carry out a row-by-row update using a cursor.

Resources