MS Access use iif statement select query as alias - ms-access-2010

I am trying to build a query to get the student results for a specific exam as a table that can be merge to a word document. The following works fine but seems very ineficient since I need to call the same query twice in the same iif statement.
Test1: IIf(Round((SELECT tblMarks.Score FROM tblMarks WHERE tblMarks.Test = 'Test1' AND [tblMarks].[ID] = [tblStudents].ID AND [tblMarks].[Rewrite] = false)*100,0)<70,70,Round((SELECT tblMarks.Score FROM tblMarks WHERE tblMarks.Test = 'Test1' AND [tblMarks].[ID] = [tblStudents].ID AND [tblMarks].[Rewrite] = false)*100,0))
To get rid of the second query call I tried the following but StudentScore is not being recognized by the IIF false condition.
Test1: IIf(Round((SELECT tblMarks.Score AS StudentScore FROM tblMarks WHERE tblMarks.Test = 'Test1' AND [tblMarks].[ID] = [tblStudents].ID AND [tblMarks].[Rewrite] = false)*100,0)<70,70, StudentScore)
I have many of those test field (test2, test3 etc...) so even just removing the extra query per field would probably help speed things up quite a bit.
Does anyone has any idea if what I am trying to do even possible??? Any help appreciated.
Thanks.
UPDATE:
I am trying to create a table/query to be use to merge into an MS Word document with fields. This new query combines many tables into one. Here's and example of the table structure:
tblStudent: StudentID, Name etc... A lot of personal info.
tblScore: StudentID, Test, Score, Rewrite etc...
New Query field are:
DISTINCT tblStudent.StudentID, tblStudent.Name, tblScore.Test(as shown above) AS Test1, tblScore.Test(Same as above but with test2) AS Test2, ... Where CourseName.....
Hope this help people see what I am trying to do; which work fine I am just trying to eliminate the second query in the if statement. Sorry this is the best I can do right now since I am not at work right now and this is where all this stuff is stored.

Related

RSQLite dbGetQuery with input from Data Frame

I have a database called "db" with a table called "company" which has a column named "name".
I am trying to look up a company name in db using the following query:
dbGetQuery(db, 'SELECT name,registered_address FROM company WHERE LOWER(name) LIKE LOWER("%APPLE%")')
This give me the following correct result:
name
1 Apple
My problem is that I have a bunch of companies to look up and their names are in the following data frame
df <- as.data.frame(c("apple", "microsoft","facebook"))
I have tried the following method to get the company name from my df and insert it into the query:
sqlcomp <- paste0("'SELECT name, ","registered_address FROM company WHERE LOWER(name) LIKE LOWER(",'"', df[1,1],'"', ")'")
dbGetQuery(db,sqlcomp)
However this gives me the following error:
tinyformat: Too many conversion specifiers in format string
I've tried several other methods but I cannot get it to work.
Any help would be appreciated.
this code should work
df <- as.data.frame(c("apple", "microsoft","facebook"))
comparer <- paste(paste0(" LOWER(name) LIKE LOWER('%",df[,1],"%')"),collapse=" OR ")
sqlcomp <- sprintf("SELECT name, registered_address FROM company WHERE %s",comparer)
dbGetQuery(db,sqlcomp)
Hope this helps you move on.
Please vote my solution if it is helpful.
Using paste to paste in data into a query is generally a bad idea, due to SQL injection (whether truly injection or just accidental spoiling of the query). It's also better to keep the query free of "raw data" because DBMSes tend to optimize a query once and reuse that optimized query every time it sees the same query; if you encode data in it, it's a new query each time, so the optimization is defeated.
It's generally better to use parameterized queries; see https://db.rstudio.com/best-practices/run-queries-safely/#parameterized-queries.
For you, I suggest the following:
df <- data.frame(names = c("apple", "microsoft","facebook"))
qmarks <- paste(rep("?", nrow(df)), collapse = ",")
qmarks
# [1] "?,?,?"
dbGetQuery(con, sprintf("select name, registered_address from company where lower(name) in (%s)", qmarks),
params = tolower(df$names))
This takes advantage of three things:
the SQL IN operator, which takes a list (vector in R) of values and conditions on "set membership";
optimized queries; if you subsequently run this query again (with three arguments), then it will reuse the query. (Granted, if you run with other than three companies, then it will have to reoptimize, so this is limited gain);
no need to deal with quoting/escaping your data values; for instance, if it is feasible that your company names might include single or double quotes (perhaps typos on user-entry), then adding the value to the query itself is either going to cause the query to fail, or you will have to jump through some hoops to ensure that all quotes are escaped properly for the DBMS to see it as the correct strings.

Use case statement for parameter for column name in sql where clause

I have been looking all day for a solution that works for my situation. I have found some things that are very similar but don't work for my situation, I tried them.
Here is the scenario; I have two table base and partdetails. I have an asp website (internal ONLY) that has drop down lists to select the parameters for a SQL query that fills a data grid view.
My problem is this, I need to be able, based on the drop down list boxes on the page, assign the column name that the criteria that is entered to be searched for.
Here is the query that I am trying to define: (This one returns 0 rows)
sqlCmd.CommandText = ("Select ba.referenceid, ba.partnum, pd.width, pd.length, CONVERT(varchar(12), pd.dateentered, 101) As [dateentered], ba.partqty, ba.status, ba.material From tbl_dlbase ba Join tbl_partdetails pd On ba.referenceid = pd.referenceid Where Case #field1 When 'part #' Then 'ba.partnum' When 'Spacing' Then 'pd.spacing' When 'Surface' Then 'pd.surface' When 'Height' Then 'pd.height' When 'Thickness' Then 'pd.thickness' End Like '%' + #criteria1 + '%'")
sqlCmd.Parameters.AddWithValue("#field1", ddlSc1.SelectedItem.Text)
sqlCmd.Parameters.AddWithValue("#criteria1", txbCriteria1.Text)
This is the latest version of the SQL statement that I have tried. I need to be able to set the field/column name based on the selection from the drop down list ddlsc1 on the asp page.
I have also been trying the queries in Studio manager to see if maybe I have fat fingered something but it also returns 0 rows so I know something is wrong with the query.
So how can I set the column name field using a parameter for the name. I know this is a huge security concern with SQL injection but this is an internal only site, and more importantly my boss said he wants it done with variables.
I don't really see a problem with this other than you have single quotes around your THEN values. Does this fix it?
SELECT ba.referenceid
,ba.partnum
,pd.width
,pd.length
,CONVERT(VARCHAR(12), pd.dateentered, 101) AS [dateentered]
,ba.partqty
,ba.STATUS
,ba.material
FROM tbl_dlbase ba
JOIN tbl_partdetails pd ON ba.referenceid = pd.referenceid
WHERE CASE #field1
WHEN 'part #'
THEN ba.partnum
WHEN 'Spacing'
THEN pd.spacing
WHEN 'Surface'
THEN pd.surface
WHEN 'Height'
THEN pd.height
WHEN 'Thickness'
THEN pd.thickness
END LIKE '%' + #criteria1 + '%'

How to pull column names from multiple tables using R

Sorry in advance due to being new to Rstudio...
There are two parts to this question:
1) I have a large database that has almost 6,000 tables in it. Many of these tables have no data in them. Is there a code using R to only pull a list of tables names that have data in them?
I know how to pull a list of all table names and how to pull specific table data using the code below..
test<-odbcDriverConnect('driver={SQL Server};server=(SERVER);database=(DB_Name);trusted_connection=true')
rest<-sqlQuery(test,'select*from information_schema.tables')
Table1<-sqlFetch(test, "PROPERTY")
Above is the code I use to access the database and tables.
"test" is the connection
"rest" shows the list of 5,803 tables names.. one of which is called "PROPERTY"
"Table1" is simply pulling one of the tables named "PROPERTY".
I am looking to make "rest" only show the data tables that have data in them.
2) My ultimate goal, which leads to the second question, is to create a table that shows a list of every table from this database in column#1 and then column 2,3,4,etc... would include every one of the column headers that is contained in each table. Any idea how do to that?
Thanks so much!
The Tables object below returns a data frame giving all of the tables in the database and how many rows are in each table. As a condition, it requires that any table selected have at least one record. This is probably the fastest way to get your list of non-empty tables. I pulled the query to get that information from https://stackoverflow.com/a/14163881/1017276
My only reservation about that query is that it doesn't give the schema name, and it is possible to have tables with the same name in different schemas. So this is likely only going to work well within one schema at a time.
library(RODBCext)
Tables <-
sqlExecute(
channel = test,
query = "SELECT T.name TableName, I.rows Records
FROM sysobjects t, sysindexes i
WHERE T.xtype = ? AND I.id = T.id AND I.indid IN (0,1) AND I.rows > 0
ORDER BY TableName;",
data = list(xtype = "U"),
fetch = TRUE,
stringsAsFactors = FALSE
)
This next part uses the tables you found above and then gets the column information from each of those tables. Lastly, it makes on single data frame with all of the column names.
Columns <-
lapply(Tables$TableName,
function(x) sqlColumns(test, x))
Columns <- do.call("rbind", Columns)
sqlColumns is a function in RODBC.
sqlExecute is a function in RODBCext that allows for parameterized queries. I tend to use that anytime I need to use quoted strings in a query.

AssertResultSetsHaveSameMetaData in TSQLT

I am using TSQLT AssertResultSetsHaveSameMetaData to compare metadata between two tables.But the problem is that i cannot hardcode the table name since i am passing the table name as the parameter at the runtime.So is there any way to do that
You use tSQLt.AssertResultSetsHaveSameMetaData by passing two select statements like this:
exec tSQLt.AssertResultSetsHaveSameMetaData
'SELECT TOP 1 * FROM mySchema.ThisTable;'
, 'SELECT TOP 1 * FROM mySchema.ThatTable;';
So it should be quite easy to parameterise the names of the tables you are comparing and build the SELECT statements based on those table name parameters.
However, if you are using the latest version of tSQLt you can also now use tSQLt.AssertEqualsTableSchema to do the same thing. You would use this assertion like this:
exec tSQLt.AssertEqualsTableSchema
'mySchema.ThisTable'
, 'mySchema.ThatTable';
Once again, parameterising the tables names would be easy since they are passed to AssertEqualsTableSchema as parameters.
If you explain the use case/context and provide sample code to explain what you are trying to do you stand a better chance of getting the help you need.

JasperReports: Convert Amount into Words

I am using iReport 4.7.
I want print amount in words.
For Example:
Assume Text field contains 1000 and i want print like "One Thousand".
Is anyone tell the steps to solve it?
Process your datasource before passing it to the report.
Using ibm's ICU4J you can convert amount into words by doing something like
double num = 2718;
RuleBasedNumberFormat formatter = new RuleBasedNumberFormat(Locale.ENGLISH, RuleBasedNumberFormat.SPELLOUT);
String result = formatter.format(num);
System.out.println(result);
Will print
two thousand seven hundred eighteen
If you are using Oracle database then try this:
SELECT TO_CHAR(TO_DATE($P{ParamName}, 'J'), 'Jsp')
FROM dual
This spells out whatever number you pass through $P{ParamName}. You can use this select clause in your main query's SELECT clause and use it.

Resources