Table aliases and field names with spaces - sql

From SAS, I am updating a table in MS Access with values from another table. Some of the fields in the table being updated contain spaces. This seems to be causing problems in the update statement. This gives me the error "Too few parameters. Expected 1.":
update [Original Table] as a inner join Updates as b on a.ID = b.ID
set a.[Variable 1] = b.[Variable 1]
where Year = "2000";
For field names without spaces, the statement works without error. And since I am using the field names elsewhere without table references/aliases, I figure the combination of [] and aliases is causing the problem. Any suggestions to address this?

Year() is a function which returns a variant subtype integer which corresponds to the calendar year of the date value you give to the function.
In your case, it seems you have a field named Year. So perhaps the "missing parameter" is the expected date argument to the Year() function.
You can avoid confusing the db engine by enclosing Year in square brackets. The brackets signal the engine that Year is an object (field) name instead of the function.
update [Original Table] as a inner join Updates as b on a.ID = b.ID
set a.[Variable 1] = b.[Variable 1]
where [Year] = "2000";
Whenever possible, it's better to use names which don't conflict with reserved words. That may not be practical in your situation ... but if you can do it you will reduce the number of Access development headaches you will suffer. :-)
For further information about "naming challenges", see Problem names and reserved words in Access.
Sorry I overlooked the point that the query can work in spite of that WHERE clause issue.
I can't see anything about the remainder of your SQL which should trigger a complaint from the db engine. I assume you tested that statement directly in Access, and got no errors.
If there is something peculiar to the interaction between SAS and Access which causes this, perhaps you could use a saved Access query as a work-around. Take that SQL and save it as a named query, qrySasTest, in your Access db. Then try executing qrySasTest from the SAS side.

This query worked as is for me (modifying only table names), both run from access and run from SAS. This is with SAS 9.3 64 bit and Office 2010 64 bit, so I suppose there could be something different going on with your version(s) of both, but it worked as expected.
proc sql;
connect to access (path="c:\temp\test.accdb");
execute
(
update [Test2] as a inner join Test as b on a.ID = b.ID
set a.[Variable 1] = b.[Variable 1]
where Year ="2000";
)
by access;
disconnect from access;
quit;

If you want to use the libname reference instead of SAS access, you can use the "dquote=ansi" option after your proc sql statement as shown below. In this example I created a library reference called mydbms:
libname mydbms odbc dsn=prompt preserve_names=yes;
proc sql dquote=ansi;
update mydbms."Original Table" as a inner join mydbms.Updates as b on a.ID = b.ID
set a."Variable 1" = b."Variable 1"
where Year = "2000";
quit;

Related

Using table variables in Oracle Stored Procedure

I have lots of experience with T-SQL (MS SQL Server).
There it is quite common to first select some set of records into a
table variable or say temp table t, and then work with this t
throughout the whole SP body using it just like a regular table
(for JOINS, sub-queries, etc.).
Now I am trying the same thing in Oracle but it's a pain.
I get errors all the way and it keeps saying
that it does not recognize my table (i.e. my table variable).
Error(28,7): PL/SQL: SQL Statement ignored
Error(30,28): PL/SQL: ORA-00942: table or view does not exist
I start thinking what at all is possible to do with this
table variable and what not (in the SP body) ?
I have this declaration:
TYPE V_CAMPAIGN_TYPE IS TABLE OF V_CAMPAIGN%ROWTYPE;
tc V_CAMPAIGN_TYPE;
What on Earth can I do with this tc now in my SP?!
This is what I am trying to do in the body of the SP.
UPDATE ( SELECT t1.STATUS_ID, t2.CAMPAIGN_ID
FROM V_CAMPAIGN t1
INNER JOIN tc t2 ON t1.CAMPAIGN_ID = t2.CAMPAIGN_ID
) z
SET z.STATUS_ID = 4;
V_CAMPAIGN is a DB view, tc is my table variable
Presumably you are trying to update a subset of the V_CAMPAIGN records.
While in SQLServer it may be useful to define a 'temporary' table containing the subset and then operate on that it isn't necessary in Oracle.
Simply update the table with the where clause you would have used to define the temp table.
E.g.
UPDATE v_campaign z
SET z.status_id = 4
WHERE z.column_name = 'a value'
AND z.status <> 4
I assume that the technique you are familiar with is to minimise the effect of read locks that are taken while selecting the data.
Oracle uses a different locking strategy so the technique is mostly unnecessary.
Echoing a comment above - tell us what you want to achieve in Oracle and you will get suggestions for the best way forward.

Sql loop through the values on a table

first off, noob alert! :))
I need to construct a query that runs on many tables. The tables vary on name just on the last digits as per client code. The thing is, the values that change aren't sequential so looping as in i=1,2,3,... does not work. A possible solution would be to have those values on a given field on an other table.
Here is the code for the first two clients 015 and 061. The leading zero(s) must are essential.
SELECT LnMov2017015.CConta, RsMov2017015.DR, RsMov2017015.NInt, "015" AS CodCli
FROM LnMov2017015 INNER JOIN RsMov2017015 ON LnMov2017015.NReg = RsMov2017015.NReg
WHERE (((LnMov2017015.CConta)="6" And (LnMov2017015.CConta)="7") AND ((RsMov2017015.DR)=9999))
UNION SELECT LnMov2017061.CConta, RsMov2017061.DR, RsMov2017061.NInt, "061" AS CodCli
FROM LnMov2017061 INNER JOIN RsMov2017061 ON LnMov2017061.NReg = RsMov2017061.NReg
WHERE (((LnMov2017061.CConta)="6" And (LnMov2017061.CConta)="7") AND ((RsMov2017061.DR)=9999))
...
So for the first SELECT the table Name is LnMov2017015, the ending 015 being the value, the client code, that changes from table to table e.g. in the second SELECT the table name is LnMov2017061 (061) being what distinguishes the table.
For each client code there are two tables e.g. LnMov2017015 and RsMov2017015 (LnMov2017061 and RsMov2017061 for the second set client shown).
Is there a way that I can build the SQL, based upon the example SQL above?
Does anyone have an idea for a solution? :)
Apparently it is possible to build a query object to read data in another db without establishing table link. Just tested and to my surprise it works. Example:
SELECT * FROM [SoilsAgg] IN "C:\Users\Owner\June\DOT\Lab\Editing\ConstructionData.accdb";
I was already using this structure in VBA to execute DELETE and UPDATE action statements.
Solution found :)
Thank you all for your input.
Instead of linking 100 tables (password protected), I'll access them with SLQ
FROM Table2 IN '' ';database=C:\db\db2.mdb;PWD=mypwd'
And merge them all with a query, before any other thing!

display passed parameter in an ssrs report even if there are no associated records in the database

I need to create an SSRS report that is passed a list of parameters and return all the parameters, even if there are no records associated with the parameter. I have posted below of what I am trying to accomplish.
Passed parameters: 12388501, 1238853, 1238858, 123885900, 12388573
And would like the final report to look like the example below:
The parameters passed in this example are Account Numbers. How can I get the Account Number to display as a record even though it is not contained in the database?
I am using SQL Server 2012 database, SSMS for development of the query and will ultimately create the report in SSRS.
I hope my wording of this question makes sense. If there is anything missing in my query please let me know and I will provide it. Thanks in advance!
Step 1: Split your string into rows of a table. My understanding is that Erland Sommarskog is regarded as an authority on handling lists in SQL Server: Arrays and Lists in SQL Server 2008
Using Table-Valued Parameters (revised in 2012. He has a page devoted to the broader topic/earlier SQL Server versions at Arrays and Lists in SQL Server.) There are other methods for splitting strings into table-valued parameters via user-defined functions, etc. that may perform reasonably well for small lists similar to what you have here.
Step 2: using that table-valued parameter that you've populated from the splitting of the string parameter, form your query like the one below. The INNER JOIN in the first SELECT will give you only those records that match an AccountNumber in your inline table and the LEFT OUTER JOIN with the WHERE clause in the second SELECT will give you only AccountNumber values that don't exist in myTable. You can substitute other values for the NULL values I've stubbed in as long as they match the data types of the corresponding fields in myTable.
SELECT mt.AccountNumber,mt.LastName,mt.FirstName,mt.ContactNumber,mt.Address,mt.City,mt.State,mt.Zip
FROM myTable mt JOIN #t t ON mt.AccountNumber = t.AccountNumber
UNION
SELECT t.AccountNumber,NULL LastName,NULL FirstName,NULL ContactNumber,NULL Address,NULL City,NULL State, NULL Zip
FROM #t t
LEFT OUTER JOIN myTable mt ON t.AccountNumber = mt.AccountNumber
WHERE mt.AccountNumber IS NULL

understanding existing SQL query

I am trying to read some exiting SQL queries written for MS SQL server.
I don't have access to database, table names etc.. Just raw query format...And I need to do some analysis on the fields required..
I need some help in understanding what certain query statements are doing...such as in the following block...
select FIELD1, x2.FIELD2
into #temp
from #temp1 x1 join #temp2 x2
on x1.FIELD1 = x2.FIELD2
and x1.FIELD3 = x2.MAXOCCUR
I have basic SQL understanding.. But I need to understand couple of things....Why does 'into' and 'from' statements have a '#' infront of table names.....what are x1 and x2 in this case. Why not just say
temp1.FIELD1 = temp2.FIELD2 instead of
x1.FIELD1 = x2.FIELD2
.....Am I missing something or is this query formed weird to begin with....I understand joins etc...
Can someone help me out...
Thanks
That is selecting from two already temp existing temp tables into a new temp table. The x1.FIELD1 is called aliasing. It's used so you don't have to type full table names when writing the query
As mentioned, the # signs indicate a TEMPORARY table.
x1 and x2 are used as "table alias" in this query. Yes, you could write
temp1.FIELD1 = temp2.FIELD2 instead of x1.FIELD1 = x2.FIELD2
but, consider if the tables had long names. Then using an alias makes the query easier to read (for humans. the computer doesn't really care).

Operation must use an updatable query. (Error 3073)

I have written this query:
UPDATE tbl_stock1 SET
tbl_stock1.weight1 = (
select (b.weight1 - c.weight_in_gram) as temp
from
tbl_stock1 as b,
tbl_sales_item as c
where
b.item_submodel_id = c.item_submodel_id
and b.item_submodel_id = tbl_stock1.item_submodel_id
and b.status <> 'D'
and c.status <> 'D'
),
tbl_stock1.qty1 = (
select (b.qty1 - c.qty) as temp1
from
tbl_stock1 as b,
tbl_sales_item as c
where
b.item_submodel_id = c.item_submodel_id
and b.item_submodel_id = tbl_stock1.item_submodel_id
and b.status <> 'D'
and c.status <> 'D'
)
WHERE
tbl_stock1.item_submodel_id = 'ISUBM/1'
and tbl_stock1.status <> 'D';
I got this error message:
Operation must use an updatable query. (Error 3073) Microsoft Access
But if I run the same query in SQL Server it will be executed.
Thanks,
dinesh
I'm quite sure the JET DB Engine treats any query with a subquery as non-updateable. This is most likely the reason for the error and, thus, you'll need to rework the logic and avoid the subqueries.
As a test, you might also try to remove the calculation (the subtraction) being performed in each of the two subqueries. This calculation may not be playing nicely with the update as well.
Consider this very simple UPDATE statement using Northwind:
UPDATE Categories
SET Description = (
SELECT DISTINCT 'Anything'
FROM Employees
);
It fails with the error 'Operation must use an updateable query'.
The Access database engine simple does not support the SQL-92 syntax using a scalar subquery in the SET clause.
The Access database engine has its own proprietary UPDATE..JOIN..SET syntax but is unsafe because, unlike a scalar subquery, it doesn’t require values to be unambiguous. If values are ambiguous then the engine silent 'picks' one arbitrarily and it is hard (if not impossible) to predict which one will be applied even if you were aware of the problem.
For example, consider the existing Categories table in Northwind and the following daft (non-)table as a target for an update (daft but simple to demonstrate the problem clearly):
CREATE TABLE BadCategories
(
CategoryID INTEGER NOT NULL,
CategoryName NVARCHAR(15) NOT NULL
)
;
INSERT INTO BadCategories (CategoryID, CategoryName)
VALUES (1, 'This one...?')
;
INSERT INTO BadCategories (CategoryID, CategoryName)
VALUES (1, '...or this one?')
;
Now for the UPDATE:
UPDATE Categories
INNER JOIN (
SELECT T1.CategoryID, T1.CategoryName
FROM Categories AS T1
UNION ALL
SELECT 9 - T2.CategoryID, T2.CategoryName
FROM Categories AS T2
) AS DT1
ON DT1.CategoryID = Categories.CategoryID
SET Categories.CategoryName = DT1.CategoryName;
When I run this I'm told that two rows have been updated, funny because there's only one matching row in the Categories table. The result is that the Categories table with CategoryID now has the '...or this one?' value. I suspect it has been a race to see which value gets written to the table last.
The SQL-92 scalar subquery is verbose when there are multiple clauses in the SET and/or the WHERE clause matches the SET's clauses but at least it eliminates ambiguity (plus a decent optimizer should be able to detects that the subqueries are close matches). The SQL-99 Standard introduced MERGE which can be used to eliminate the aforementioned repetition but needless to say Access doesn't support that either.
The Access database engine's lack of support for the SQL-92 scalar subquery syntax is for me its worst 'design feature' (read 'bug').
Also note the Access database engine's proprietary UPDATE..JOIN..SET syntax cannot anyhow be used with set functions ('totals queries' in Access-speak). See Update Query Based on Totals Query Fails.
Keep in mind that if you copy over a query that originally had queries or summary queries as part of the query, even though you delete those queries and only have linked tables, the query will (mistakenly) act like it still has non-updateable fields and will give you this error. You just simply re-create the query as you want it but it is an insidious little glitch.
You are updating weight1 and qty1 with values that are in turn derived from weight1 and qty1 (respectively). That's why MS-Access is choking on the update. It's probably also doing some optimisation in the background.
The way I would get around this is to dump the calculations into a temporary table, and then update the first table from the temporary table.
There is no error in the code. But the error is Thrown because of the following reason.
Please check weather you have given Read-write permission to MS-Access database file.
The Database file where it is stored (say in Folder1) is read-only..?
suppose you are stored the database (MS-Access file) in read only folder, while running your application the connection is not force-fully opened. Hence change the file permission / its containing folder permission like in C:\Program files all most all c drive files been set read-only so changing this permission solves this Problem.
In the query properties, try changing the Recordset Type to Dynaset (Inconsistent Updates)