SELECT IPD.Task_grp "Task Group", TASK.STARTW "Starting Area", TASK.ENDW "Destination Area", IPD.Nxt_Work_Grp,IPD.Nxt_Work_Area
"Drop Area", IPD.Prty "Priority", IPD.Stat_Code "Status"
FROM int_path_defn IPD,
(SELECT start_curr_work_grp || start_curr_work_area StartW,
start_dest_work_grp ||start_dest_work_area EndW
FROM task_hdr WHERE task_id='332800') TASK WHERE IPD.CURR_WORK_GRP || IPD.Curr_Work_Area=TASK.StartW
AND IPD.Dest_Work_Grp || IPD.Dest_Work_Area=TASK.ENDW
I am getting
Msg 102, Level 15, State 1, Line 5
Incorrect syntax near '|'.`
Please help what could be the wrong. same query executed successfully in oracle sql developer
SQL Server uses + for string concatenation instead of ||.
The syntax is wrong. "||" - even "|" - has no sense in TSQL.
Which means either the person writing this SQL has no clue OR - more likely - it is coming from another server type. Bad news: SQL is not really standardized, everyone has his own extensions.
Time to do your job and fixing the syntax. And yes, this can be tendious work.
Related
I'm using SQL Server within my Laravel application. I need to group/sum a table for the month/year. My query looks like this:
$positions = BelegPos::select(
DB::raw("YEAR(Datum) as year"),
DB::raw("MONTH(Datum) as month"),
DB::raw("SUM(Menge) as stunden")
)->groupBy("year", "month")
->get();
I'll get the following error message:
SQLSTATE[42S22]: [Microsoft][ODBC Driver 17 for SQL Server][SQL
Server]Invalid column name 'year'.
I don't know what's wrong, as the query the way I build it works fine with MySQL servers.
Thanks for any hint in the right direction.
UPDATE
I researched a bit more and read about somthing that points out, that the Select Statement isn't available in the GROUP BY section and that you have to add the same query there. so my query looks now like this:
$positions = selectlineBelegPos::select(
DB::raw("YEAR(Datum) as the_year"),
DB::raw("MONTH(Datum) as the_month"),
DB::raw("SUM(Menge) as stunden")
)
->groupBy(DB::raw("YEAR(Datum) as the_year"),DB::raw("MONTH(Datum) as the_month"))
->get();
Still not the solution but the error message has changed to this:
SQLSTATE[42000]: [Microsoft][ODBC Driver 17 for SQL Server][SQL
Server]Incorrect syntax near the keyword (SQL: select
YEAR(Datum) as the_year, MONTH(Datum) as the_month, SUM(Menge) as
stunden from [BELEGP]
So I think there is just one small thing wrong but can't figure out what.
Any ideas?
Solution
Just found the the solution:
$positions = selectlineBelegPos::select(
DB::raw("YEAR(Datum) AS year"),
DB::raw("MONTH(Datum) AS month"),
DB::raw("SUM(Menge) AS stunden")
)
->groupBy(DB::raw("YEAR([Datum])"),DB::raw("MONTH([Datum])"))
->get();
Indeed isn't the dynamically value names (year and month) unavailable in the GROUPBY clause, instead you have to call the DB::raw again but now without generating the key words again.
thank you all for the support!
I'm trying to restore a database with a - in the name. If I have no - in the name, the database is correctly restored.
If I put '' around the database it still doesn't work. I'm still searching what to do but I can't find it.
$sqlRestoreCommand.CommandText = "RESTORE DATABASE '$databaseName' FROM DISK = '$databaseBackup' " ;
The following exception occurs and the code is below:
Exception: Exception calling "ExecuteNonQuery" with "0" argument(s): "Incorrect syntax near '-'.
Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.".Exception.Message
$databaseName = "TempRpc-RC";
# Write the state for debugging purposes.
"SQL State" > sqlstatelog.txt;
$connection.State >> sqlstatelog.txt;
# Create the SQL restore command.
$sqlRestoreCommand = $connection.CreateCommand();
# Set the command text to a SQL restore command and fill in the parameters.
# With move option is needed!
$sqlRestoreCommand.CommandText = "RESTORE DATABASE $databaseName FROM DISK = '$databaseBackup' " ;
$sqlRestoreCommand.CommandText += "WITH FILE = 1, ";
$sqlRestoreCommand.CommandText += "MOVE N'$databaseName" + "'" + " TO N'C:\Program Files\Microsoft SQL Server\MSSQL14.SQLEXPRESS\MSSQL\Data\$databaseName" + "_Data.mdf', ";
$sqlRestoreCommand.CommandText += "MOVE N'$databaseName" + "_log'" +" TO N'C:\Program Files\Microsoft SQL Server\MSSQL14.SQLEXPRESS\MSSQL\Data\$databaseName" +"_Log.ldf'";
$sqlRestoreCommand.Connection = $connection;
# Execute the commands.
$sqlRestoreResult = $sqlRestoreCommand.ExecuteNonQuery();
# Write the query
Write-Verbose $sqlRestoreCommand.CommandText;
tl;dr:
Inside the expandable PowerShell string ("...") that defines the query string, replace '$databaseName' with [$databaseName]
As an aside: Unless you fully control all parts used to construct the query string, you should use parameters to avoid SQL injection attacks, as Ansgar advises.
Ansgar Wiechers provided the crucial pointer:
Since your database name contains a - character, it isn't a regular identifier, so it must be quoted / delimited, i.e., it must be specified as a delimited identifier.
Additionally, identifiers that conflict with reserved keywords must be specified as delimited identifiers too.
A delimited identifier is one enclosed in either [...] or "..."; by contrast, '...' is not supported, which explains your symptoms.
Note: [...] is SQL Server-specific, but is always supported there, whereas the standard "..." is only supported when SET QUOTED_IDENTIFIER ON is in effect in T-SQL, which is true by default, however - except in certain situations, such as when using sqlcmd.exe without -l.
I have Sybase database 15 and one of oracle query wanted to convert into sybase Database.
I have tried all option but not able to find google so i need your help
select Log_record_id,
Event_time,
SUBSTR (Object_of_reference,(LOCATE (Object_of_reference, '=', 1, 2) + 1),((LOCATE (Object_of_reference, ',', 1, 2) - LOCATE (Object_of_reference, '=', 1, 2)) - 1)) as NENAME,
Perceived_severity,
Specific_problem,
'' as Cease_time,
Alarm_id,
SP_text,
Alarm_state
from FMA_alarm_list
where Log_record_id > 63314472
Getting Error
Msg 14216, Level 16, State 1: Server 'SYBASESERVER', Line 1: Function
'INSTR' not found. If this is a SQLJ function or SQL function, use
sp_help to check whether the object exists (sp_help may produce a
large amountof output).
Very often we are unable to use Partitioned reads in Netezza connector.
Example
When partitioned read = Yes and Generated SQL at Runtime = Yes this works:
SELECT "Firma", "KundeNr", "ArtikkelNr"," LagerstedNr"
FROM dwhusr."TI_FT_Salg"
When Generated SQL at Runtime = No and the query is Autogenerated by DataStage (or we write it our selves) the query looks like this:
SELECT "Firma", "KundeNr", "ArtikkelNr"," LagerstedNr"
FROM dwhusr."TI_FT_Salg"
WHERE mod(datasliceid,[[node-count]])=[[node-number]]
It will then throw an error:
DB_TI_FT_Salg: Unexpected ODBC error occurred. Reason: [SQLCODE=42000][Native=27] ERROR: 'SELECT "Firma", "KundeNr", "ArtikkelNr"," LagerstedNr" FROM dwhusr."TI_FT_Salg" where mod(datasliceid,[[node-count]])=[[node-number]] limit 0'
error ^ found "[" (at char 102) expecting an identifier found a keyword (CC_NZMetadataHelper::describeResultSet, file CC_NZMetadataHelper.cpp, line 5 622)
Please help!
I am working on pyodbc in Eclipse (4.3.2v20140221-1852) with PyDev on Win 7. My python is 3.2.5.
At my code:
cursor.execute("select top " + str(1) + " a.my_id, a.mycode" +
"from my_table as a where a.mycode = ?", aGivenCode)
I got an error :
pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver]
[SQL Server]Incorrect syntax near the keyword 'as'. (156) (SQLExecDirectW)")
Why I got error at " as a " ?
thanks !
A couple suggestions for future development:
Use multi-line string notation """ to allow better identification of syntax errors (like the missing space between column and table in the original query).
Instead of string concatenation, use a parameter for TOP values. The value must be wrapped in parentheses.
With these guidelines, your original code would be updated to:
top = 1
cursor.execute("""select top (?) a.my_id, a.mycode
from my_table as a
where a.mycode = ?""",
(top, aGivenCode))
Try this? I think you're missing a space in there:
cursor.execute("select top " + str(1) + " a.my_id, a.mycode from my_table as a where a.mycode = ?", aGivenCode)
See how there is no space in between 'a.mycode' and 'from my_table'? I'm not 100% sure that is right, but give it a try.
These things are also easier to debug like this:
sql = "select top " + str(1) + " a.my_id, a.mycode from my_table as a where a.mycode = ?"
print sql
cursor.execute(sql, aGivenCode)