Update linked SQL server with parameters - sql

I have two linked SQL servers and i am trying to issue an update on the other server but am getting an error "Statement(s) could not be prepared.", followed by "Must declare the scalar variable "#Shipper_Nbr""
The syntax i am using is:
update DBSERVER.DBNAME.DBO.TABLE set Field = #Value WHERE ID = #id
What is the correct way to do this?
UPDATE:
I tried using a stored procedure and get the same result. Also, i noticed additional information. The syntax checks out, i only get the error when i attempt to save the stored procedure. Also, i noticed the error also states "OLE DB provider "SQLNCLI" for linked server "WARSQLVS01" returned message "Deferred prepare could not be completed."."
ACK - i figured it out. It was a separate line where i was trying to pass the parameter from within OPENQUERY select statement. Sorry about that! :-\

Not entirely sure what this problem is, but we have had to work round similar kinds of issues by setting up a stored proc on the remote server and calling that, rather than trying to manipulate the items on the remote server locally.

Are you sure the problem is with the server link, and not something about the rest of your SQL statement? Where is the #Shipper_Nbr value assigned?

Se if this works
UPDATE T
SET Arrive_DT = #Actual_DateTime
WHERE Shipper_Nbr = #Shipper_Nbr and Container_Name = #Container_Name
FROM WARSQLVS01.ISS3_AND_DHAM_PROD.dbo.ISS_AND_data_Shipments as T

Related

Why do i keep getting a parameter error in my sql update?

I have been trying to use SQL with PYQT4 to update an access database with information a user has inputted into my program. I don't want to update all of the records just a specific record and a specific amount of columns (5 out of the 10 columns). however, I keep getting an error that reads:
"pyodbc.Error: ('07002', '[07002] [Microsoft][ODBC Microsoft Access
Driver] Too few parameters. Expected 6. (-3010) (SQLExecDirectW)')"
I can't seem to resolve it.
Here is my code:
SelectDatabase.execute('UPDATE Order_Table SET DateDue=(dateDueString), TimeDue=(timeDueString), PaymentType=(paymentExp), Paid=(paidExp), Customer_ID=(customerExp) WHERE OrderLine_ID=(orderlineExp)')
The values inside the brackets are variables that I have created and I am trying to call upon them, I have proof checked them multiple times, including spell checking them and I can't find a problem in that regard.
If anyone has any ideas or needs more information please let me know.
I have managed to figure out the problem. I was trying to use a variable within my SQL which once I had formatted differently worked straight away this is what I changed it to.
SelectDatabase.execute('UPDATE Order_Table SET DateDue=?, TimeDue=?, PaymentType=?, Paid=?, Customer_ID=? WHERE OrderLine_ID=?', dateDueString,timeDueString,paymentExp,paidExp,customerExp,orderlineExp)
This way by changing the values to unknowns inside the SQL procedure and referencing them in order after the edit allowed for the string values of the variables to be found and the correct columns to be edited.
Thank-you for trying to help.
Well i guess you need create your stored procedure in SQL first with all parameters and then simply call it.
Exec dbo.mYParameter 'timeDueString','paymentExp','paidExp','customerExp','orderlineExp'

Syntax Error While Calling DB2 Stored Procedure Through JMeter

I am trying to call a DB2 Stored Procedure which has two Input parameters (Timestamp, both) and one Output parameter (Integer). I am trying to do so from JMeter JDBC Sampler and getting sql syntax exception.
Response code: 42884 -440
Response message: com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-440, SQLSTATE=42884, SQLERRMC=PROCEDURE;DEVSCHEMA.GET_ROW_COUNT, DRIVER=4.19.26
Response headers:
1272084586, URL=jdbc:db2://<db2IP>:<port>/DB2T, UserName=<someUserName>, IBM Data Server Driver for JDBC and SQLJ
From IBM Documentation I got to know that this error happens when either Stored procedure is not present - which is not the case, Schema name incorrect - which is also not the case, mismatching number of parameters - I verified this but I am doubtful at this point because JMeter provides separate fields to be filled up and in one of the fields I might be passing incorrect value.
I have not much knowledge of JMeter but with the help from apache JMeter documentation I have set below values to the Sample Fields.
Query Type: Callable Statement
Query: CALL DEVSCHEMA.GET_ROW_COUNT(?,?,?)
Parameter Values: ${__time(yyyy-MM-dd HH:mm:ss,)},${__time(yyyy-MM-dd HH:mm:ss,)},0
Parameter Types: IN TIMESTAMP,IN TIMESTAMP,OUT INTEGER
Variable Names:VARCOUNT
Handle ResultSet: Store as a String
Can anyone please figure out where am I making a mistake? Many thanks.
The issue has been resolved. It was literally something else about which I never gave a thought. When I got the same error when I tried to access the same SP using Java code, I contacted DB2 team who wrote the Stored procedure. And issue was with the SP. According to them execute access was given so after drilling here and there they preferred to create a new SP which worked without any issues. Else everything was perfect from JMeter side.

How to invoke stored procs with parameter using T-SQL scripting?

We are using edge-sql to execute T-SQL scripts and also stored procedures via C#. I noticed recently that stored proc support has been added and I'm trying to execute would would be:
exec dbo.sgRouteExportDelete #TripDate='2014-05-06', #RouteId = 1234, #Action='DELETE', #Comment='xxxxxx';
in SQL Server Management Studio, using edge-sql 0.1.2.
I've played around with several variations, but I get one of 2 error messages. Either cannot find stored procedure '' or "cannot find stored procedure 'sgRouteExportDelete #TripDate='2014-05-06', #RouteId = 1234, #Action='DELETE', #Comment='xxxxxx'" The stored proc executes just fine in edge.sql when invoked via C# method.
I did some additional experimentation and found I can execute a stored proc with no parameters: exec dbo.sgVersionGet, but any stored procs with parameters return errors.
So what am I doing wrong? And how could I invoke with parameter values that aren't hard-coded, as above? Both SQL Server and edge use the # character for parsing params.
Any help appreciated ...
-BillyB
In SQL Server when you are referring to a database object without the object full path ([database.schema].object), SQL Server will try to locate the object using the Default/Initial Catalog value which points to the default database if that was not specified within the connection string then chances are that when you try running your statement SQL Server won't be able to find the object throwing the "Cannot find XX" error, You should either specify an initial catalog on your connection string or execute your procedures using the full path, database.schema.procedure E.g. mydatabase.dbo.sp_customerCleanUp. On the other hand there is an internal procedure sp_executesql that you can use to run your procedures without having to hard code the parameters, all you need to do is build a string concatenating the hard coded part of the string (the procedure name) and whatever number of variables you are passing as parameters, see example ( https://technet.microsoft.com/en-us/library/ms175170%28v=sql.105%29.aspx )
The variables are assumed when calling a stored procedure with edge-sql. Any parameter you would preface with an '#' symbol will need to have the same name within the stored procedure.

SQL Server reports 'Invalid column name', but the column is present and the query works through management studio

I've hit a bit of an impasse. I have a query that is generated by some C# code. The query works fine in Microsoft SQL Server Management Studio when run against the same database.
However when my code tries to run the same query I get the same error about an invalid column and an exception is thrown. All queries that reference this column are failing.
The column in question was recently added to the database. It is a date column called Incident_Begin_Time_ts .
An example that fails is:
select * from PerfDiag
where Incident_Begin_Time_ts > '2010-01-01 00:00:00';
Other queries like Select MAX(Incident_Being_Time_ts); also fail when run in code because it thinks the column is missing.
Any ideas?
Just press Ctrl + Shift + R and see...
In SQL Server Management Studio, Ctrl+Shift+R refreshes the local cache.
I suspect that you have two tables with the same name. One is owned by the schema 'dbo' (dbo.PerfDiag), and the other is owned by the default schema of the account used to connect to SQL Server (something like userid.PerfDiag).
When you have an unqualified reference to a schema object (such as a table) — one not qualified by schema name — the object reference must be resolved. Name resolution occurs by searching in the following sequence for an object of the appropriate type (table) with the specified name. The name resolves to the first match:
Under the default schema of the user.
Under the schema 'dbo'.
The unqualified reference is bound to the first match in the above sequence.
As a general recommended practice, one should always qualify references to schema objects, for performance reasons:
An unqualified reference may invalidate a cached execution plan for the stored procedure or query, since the schema to which the reference was bound may change depending on the credentials executing the stored procedure or query. This results in recompilation of the query/stored procedure, a performance hit. Recompilations cause compile locks to be taken out, blocking others from accessing the needed resource(s).
Name resolution slows down query execution as two probes must be made to resolve to the likely version of the object (that owned by 'dbo'). This is the usual case. The only time a single probe will resolve the name is if the current user owns an object of the specified name and type.
[Edited to further note]
The other possibilities are (in no particular order):
You aren't connected to the database you think you are.
You aren't connected to the SQL Server instance you think you are.
Double check your connect strings and ensure that they explicitly specify the SQL Server instance name and the database name.
In my case I restart Microsoft SQL Sever Management Studio and this works well for me.
If you are running this inside a transaction and a SQL statement before this drops/alters the table you can also get this message.
I eventually shut-down and restarted Microsoft SQL Server Management Studio; and that fixed it for me. But at other times, just starting a new query window was enough.
If you are using variables with the same name as your column, it could be that you forgot the '#' variable marker. In an INSERT statement it will be detected as a column.
Just had the exact same problem. I renamed some aliased columns in a temporary table which is further used by another part of the same code. For some reason, this was not captured by SQL Server Management Studio and it complained about invalid column names.
What I simply did is create a new query, copy paste the SQL code from the old query to this new query and run it again. This seemed to refresh the environment correctly.
In my case I was trying to get the value from wrong ResultSet when querying multiple SQL statements.
In my case it seems the problem was a weird caching problem. The solutions above didn't work.
If your code was working fine and you added a column to one of your tables and it gives the 'invalid column name' error, and the solutions above doesn't work, try this: First run only the section of code for creating that modified table and then run the whole code.
Including this answer because this was the top result for "invalid column name sql" on google and I didn't see this answer here. In my case, I was getting Invalid Column Name, Id1 because I had used the wrong id in my .HasForeignKey statement in my Entity Framework C# code. Once I changed it to match the .HasOne() object's id, the error was gone.
I've gotten this error when running a scalar function using a table value, but the Select statement in my scalar function RETURN clause was missing the "FROM table" portion. :facepalms:
Also happens when you forget to change the ConnectionString and ask a table that has no idea about the changes you're making locally.
I had this problem with a View, but the exact same SQL code worked perfectly as a query. In fact SSMS actually threw up a couple of other problems with the View, that it did not have with the query. I tried refreshing, closing the connection to the server and going back in, and renaming columns - nothing worked. Instead I created the query as a stored procedure, and connected Excel to that rather than the View, and this solved the problem.

sql server 2005 express - Invalid Object Name error

I have a copy of a query from a view (by filtering) and when i tried to excute it, it throws an error message that says "invalid object name 'bla bla'".
How can i fix it?
I am using windows 7(ultimate) os and sql server 2005 express.
You may be executing the query in the wrong database. If you are running it manually in SSMS, use the 'use' statement or the 'available databases' drop down list to select the correct db.
Or fully qualify the name of the object you are accessing (db_name.owner.object_name).
Or, as rlb.usa suggests, maybe the object just doesn't exist. (check your spelling...)
It can happen two ways:
You have table, procedure, or function name(s) that do not exist.
You can fix this by verifying the object does indeed exist. Check this one first. Is the spelling correct? Is the schema correct? (dbo.mytable != user.mytable)
SQL wants you to use "qualified" names.
You can fix this by putting use mydatabasename; at the top of your query, before the query itself. If it doesn't like that one, you can then try the longer method of using qualified names by prefixing all of your tables, functions, and procedures as databasename.schema.object .