postgresql 9. update not working - database

I am using PostgreSQL 9.
When trying to do this update, row table does not get updated.
$cmd = "UPDATE table1 SET field1 = '$value1' WHERE key_field = '$key_value'; ";
table1 has privileges for PUBLIC to INSERT and UPDATE.
When using pgAdmin III SQL console it does perfectly the job.

Don't use variable parsing (or string concatenation) to build SQL queries;
What does "using PgAdminIII sql console it does perfectly the job" mean? You have pasted the same query in pgAdmin3 and it worked? I very much doubt pgAdmin3 understands PHP and does PHP-style variable parsing as a consequence.
If it was not exactly the same query (most probably it was one with the PHP variables replaced with literals) what was the query you tested in pgAdmin3?
Most probably the reason the update is ineffective is that there are no rows that satisfy your WHERE clause.

$cmd = "UPDATE table1 SET field1 = '$value1' WHERE key_field = '$key_value'";
Now try there was an extra ;

Related

Using UDF's in Excel SQL Server DB query [duplicate]

How can I execute the following SQL inside a single command (single execution) through ADO.NET?
ALTER TABLE [MyTable]
ADD NewCol INT
GO
UPDATE [MyTable]
SET [NewCol] = 1
The batch separator GO is not supported, and without it the second statement fails.
Are there any solutions to this other than using multiple command executions?
The GO keyword is not T-SQL, but a SQL Server Management Studio artifact that allows you to separate the execution of a script file in multiple batches.I.e. when you run a T-SQL script file in SSMS, the statements are run in batches separated by the GO keyword. More details can be found here: https://msdn.microsoft.com/en-us/library/ms188037.aspx
If you read that, you'll see that sqlcmd and osql do also support GO.
SQL Server doesn't understand the GO keyword. So if you need an equivalent, you need to separate and run the batches individually on your own.
Remove the GO:
String sql = "ALTER TABLE [MyTable] ADD NewCol INT;";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
sql = "UPDATE [MyTable] SET [NewCol] = 1";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
It seems that you can use the Server class for that. Here is an article:
C#: Executing batch T-SQL Scripts containing GO statements
In SSMS (SQL Server Management System), you can run GO after any query, but there's a catch. You can't have the semicolon and the GO on the same line. Go figure.
This works:
SELECT 'This Works';
GO
This works too:
SELECT 'This Too'
;
GO
But this doesn't:
SELECT 'This Doesn''t Work'
;GO
This can also happen when your batch separator has been changed in your settings. In SSMS click on Tools --> Options and go to Query Execution/SQL Server/General to check that batch separator.
I've just had this fail with a script that didn't have CR LF line endings. Closing and reopening the script seems to prompt a fix. Just another thing to check for!
Came across this trying to determine why my query was not working in SSRS. You don't use GO in SSRS, instead use semicolons between your different statements.
I placed a semicolon ; after the GO, which was the cause of my error.
You will also get this error if you have used IF statements and closed them incorrectly.
Remember that you must use BEGIN/END if your IF statement is longer than one line.
This works:
IF ##ROWCOUNT = 0
PRINT 'Row count is zero.'
But if you have two lines, it should look like this:
IF ##ROWCOUNT = 0
BEGIN
PRINT 'Row count is zero.'
PRINT 'You should probably do something about that.'
END
I got this error message when I placed the 'GO' keyword after a sql query in the same line, like this:
insert into fruits (Name) values ('Apple'); GO
Writing this in two separate lines run. Maybe this will help someone...
I first tried to remove GO statements by pattern matching on (?:\s|\r?\n)+GO(?:\s|\r?\n)+ regex but found more issues with our SQL scripts that were not compatible for SQL Command executions.
However, thanks to #tim-schmelter answer, I ended up using Microsoft.SqlServer.SqlManagementObjects package.
string sqlText;
string connectionString = #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=FOO;Integrated Security=True;";
var sqlConnection = new System.Data.SqlClient.SqlConnection(connectionString);
var serverConnection = new Microsoft.SqlServer.Management.Common.ServerConnection(sqlConnection);
var server = new Microsoft.SqlServer.Management.Smo.Server(serverConnection);
int result = server.ConnectionContext.ExecuteNonQuery(sqlText);

invoke-sqlcmd fails shows no results on certain type of queries

Invoke-Sqlcmd -ServerInstance '.' -Database 'MyDB'
-Query 'EXEC SprocA #param1= "value";EXEC SprocB #param1= "value";'
Basically I have my Invoke-SqlCmd running a query that invokes two stored procedures. Both the stored procedures output a bunch of rows.
However if sprocA does not output any results (empty select results or no rows), then the invoke command does not seem to print the output of the second sprocB even if it has data.
If I change the order of the stored procedures in my Invoke-SqlCmd commands query parameter, then this works perfectly and returns the output of the first stored procedure.
If I had three stored procedure calls where the first returns data and the second does not and the third does, it prints output of the first result and third result.
Basically it does not print any output only if the first stored procedure has no output. Seems weird.
Anything I can do to get around this SQL wise ? Could be a PowerShell thing?
I was also able to repro this with two Select statements where one returns data and the other does not.
This is the documented behavior of invoke-sqlcmd
When this cmdlet is run, the first result set that the script returns
is displayed as a formatted table. If subsequent result sets contain
different column lists than the first, those result sets are not
displayed. If subsequent result sets after the first set have the same
column list, their rows are appended to the formatted table that
contains the rows that were returned by the first result set.
It looks like both result sets are actually returned, but not output by defaut.
EG
PS C:\> Invoke-SqlCmd "select 1 a; select 2 b, 3 c;" | % { $_ | Out-Default }
outputs
a
-
1
b c
- -
2 3
Actually, it is hard to believe MS made such a mistake or maybe it's not a mistake. Whatever, when you run Invoke-SqlCmd and with a query like the following,
select * from table1 where id = 1111 -- non-exists id, this select returns nothing
select * from table2 where id = 2222 -- exists id, this select returns something
On SSMS you can see 2 result sets, the first one is empty.
However, the Invoke-SqlCmd doesn't return anything when the first result set is empty, even other result sets are not. My face was like ?_?
Another approach is to write you own invoke SQL function like following to return whatever result sets, even the empty ones.
$sql_Conn = New-Object System.Data.SqlClient.SQLConnection
$sql_Conn.ConnectionString = $sqlConnectionString
$sql_Conn.Open()
$sql_cmd = New-Object system.Data.SqlClient.SqlCommand($Query, $sql_Conn)
$sql_ds = New-Object system.Data.DataSet
$sql_da = New-Object system.Data.SqlClient.SqlDataAdapter($sql_cmd)
[void]$sql_da.fill($sql_ds)
$sql_Conn.Close()
return $sql_ds
Everything is fine until a new problem comes about the keyword GO in your script, you must know it if you use SSMS. The thing is, this GO is not a SQL command. it is just a separator used by SSMS. MS developed codes can handle the GO in a good manner, e.g. SSMS, Invoke-SqlCmd and sqlcmd.exe. If you use your own SQL invoke function you will get syntax issue
Incorrect syntax near 'GO'
While people most likely to ask you to update the SQL script to remove all GO lines, however, things are not always under controlled, normally need to work with different people and teams.
At last, I have to trim the GO in my scripts like the following
$Query = $Query -ireplace "(^|\r|\n)[ \t]*\bGO\b[ \t]*(\r|\n|$)", '$1$2'
https://github.com/LarrysGIT/Invoke-Sql
Of course, the story is not over, the more I am trying to automate SQL related tasks. The more issue found. There are multiple ways to automatically execute SQL script. None of them are perfect so far.
Invoke-Sql (My own script)
* Is able to handle the key separator 'GO'
* Is able to handle duplicate columns
* Fully support multiple result sets, even the first result set is empty
* Unable to handle `Create or alter` keywords if there are contents ahead
* Unable to handle special characters like '194 160' (non-breaking space) in SQL script (edited by some document edit tool, MS word for example)
Invoke-SqlCmd
* Is able to handle the key separator 'GO'
* Is able to handle special characters like 'non-breaking space'
* Unable to handle duplicate columns
* Unable to fully handle multiple result sets (when the first table is empty)
sqlcmd.exe
* Is able to handle all things (briefly tested)
* The returned result sets are plain text, hard to parse
Microsoft.SqlServer.SMO snapin
* The API of SQL server management studio
* Theoretically should be able to handle all cases
* Need to dig more

ORACLE to MSSQL using SSMS Import Wizard with Query to Update Rows

I have a situation which prevent me of updating rows in a table in MSSQL getting the data from ORACLE. I can INSERT fine from ORACLE to MS SQL using a SELECT statement like:
SELECT XRECORDACTIVATIONDATE, XRECORDCUTOFFDATE, XRECORDREVIEWDATE,
XRECORDFILINGDATE, XNOLATESTREVISIONDATE, XNEWREVISIONDATE, XDATERECEIVEDDOC,
XINACTIVEDATE, DCREATEDATE, DINDATE, DRELEASEDATE, DLASTMODIFIEDDATE
FROM STELLENT.V_EXPORT_TO_MSSQL V
But when I try to update the rows based on an unique ID using:
UPDATE D
SET D.XRECORDACTIVATIONDATE = V.XRECORDACTIVATIONDATE
FROM DBO.DOCUMENT D
INNER JOIN STELLENT."V_EXPORT_TO_MSSQL" V ON D.DID = V.DID
I get the following error:
ORA-00933: SQL command not properly ended
(System.Data.OracleClient)
DBO.DOCUMENT is a MSSQL table.
STELLENT.V_EXPORT_TO_MSSQL is a View in ORACLE
I might be writing wrong the query I will appreciate some help. thank you.
Lukasz is correct - a select statement is a lot different from an insert statement.
The ORA-00933 error means your query is not formed properly. This is because in Oracle, the database expects queries to follow a certain format/standard. Typically, queries within Oracle will have a form of SELECT [columns] FROM [tables] WHERE [conditions]. This can vary - for example if you wanted to select all data from a table, that query might look like "SELECT * FROM [table];" and the WHERE clause can be omitted because you do not need to define a condition for the database to return all rows. While queries can vary in form, in general, they will follow some type of format.
You are receiving this error because your query does not conform to the expected form, and it is because you have an INNER JOIN that directly follows your FROM clause. To fix this, I would recommend creating a query that you use to select the records you want to update, and then using that select statement to form your update statement by replacing the "SELECT" with "UPDATE".
For more on SQL Standards and how to format your queries, I would recommend taking a look at Oracle documentation. https://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_1001.htm#SQLRF52344

SQL Server query behaves differently interactively than over JDBC - omits some tables

I've been trying to retrieve constraint data for all tables using an SQL query over JDBC.
My test database has only 3 tables.
If I execute the query interactively using MS SQL Server Management Studio, I get all the results that I expect (ie. 3 rows - there's a primary key in each of 3 tables).
if I use the JDBC method to specifically retrieve primary keys (as below) then I also correctly get 3 results:
ResultSet rs = dbmd.getPrimaryKeys(jdbcCatalog, jdbcSchema, jdbcTableName);
If I use the exact same SQL statement (that I used interactively and got 3 results back) as a query over JDBC (using executeQuery() shown below) then I only get 1 result instead of the expected 3.
String query =
"select PK.CONSTRAINT_NAME, PK.TABLE_SCHEMA, PK.TABLE_NAME " +
"from information_schema.TABLE_CONSTRAINTS PK";
ResultSet rs = null;
try {
Statement stmt = con.createStatement();
rs = stmt.executeQuery(query);
}catch (Exception exception) {
// Exception handler code
}
while (rs.next()){
// Only executes once.
}
I would be very grateful if someone could explain why the SQL query over JDBC is performing differently to the exact same SQL query performed interactively. Could it be a security/ownership issue? (although the JDBC call getPrimaryKeys() doesn't suffer this)
Thanks.
I don't see where you're setting your database context, but I suspect that that's the issue. As a test, you can change your statement to "select db_name()" and see what it returns. If it's not the database that you think that you should be in, that's your issue.

Using Parameters in MS Reporting Services (SQL Server 2008) against an ODBC data source

I writing a report in Visual Studio that takes a user input parameter and runs against an ODBC datasource. I would like to write the query manually and have reporting services replace part of the where clause with the parameter value before sending it to the database. What seems to be happening is that the #parmName I am assuming will be replaced is actually being sent as part of the SQL statement. Am I missing a configuration setting somewhere or is this simply not possible?
I am not using the filter option in the tool because this appears to bring back the full dataset from the database and do the filtering on the SQL Server.
It sounds like you'll need to treat the SQL Statement as an expression. For example:
="Select col1, col2 from table 1 Where col3 = " & Parameters!Param1.Value
If the where clause is a string you would need to do the following:
="Select col1, col2 from table 1 Where col3 = '" & Parameters!Param1.Value & "'"
Important: Do not use line breaks in your SQL expression. If you do you will get an error.
Holla back if you need any more assistance.
Doesn't ODBC use the old "?" syntax for parameters? Try this:
select col1, col2 from table1 where col3 = ?
The order of your parameters becomes important then, but it's less vulnerable to SQL injection than simply appending the parameter value.
Encountered same problem trying to query an access database via ODBC.
My original query: SELECT A.1 FROM A WHERE A.1 = #parameter resulted in error. Altered to: SELECT A.1 FROM A WHERE A.1 = ?.
You then have to map the query parameter with your report parameter.
I am a bit confused about this question, if you are looking for simple parameter usage then the notation is :*paramName* , however if you want to structurally change the WHERE clause (as you might in sql+ using ?) then you should really be using custom code within the report to define a function that returns the required sql for the query.
Unfortunately, when using custom code, parameters cannot be referenced directly in the generated query but have to have there values concatenated into the resultant String, thus introducing the potential for SQL injection.

Resources