How to write a parameterized SQL query? - sql-server

I am trying this query to fetch my value from a MS SQL database on basis of two conditions but still I am getting exception in the syntax part.
Can anybody tell me what is the correct way to write a parameterized query in R?
Following is the query I used:
query<- paste0("SELECT [value] FROM [RiskDashboard].[dbo].[tbl_Simulation]
where Row_Id=", row_id[c(1),] ," AND Script_Id=", script_id[c(1),] ,)
T_data<-sqlQuery(ch,query)
print(T_data)

Parameterizing data is very important - especially from a security perspective. The examples you have are string concatenations and are subject to SQL injections.
The RODBCext package does have support for parameterization.
First - standard SQL parameterization syntax:
SELECT ColA, ColB FROM MyTable where FirstName = ? and LastName = ?
Each ? mark indicates in order the values that will appear in a vector. This syntax is true for ODBC regardless of platform. Others have extended to support position. eg. OLEDB supports #P1, #P2 etc.
While maybe not important for your R queries - in a multi-user system parameterized queries execute faster because the query plan is stored by the database-server (true of both Oracle and SQL Server).
To semi-plagiarize from the documentation:
library(RODBCext)
connHandle <- odbcConnect("myDatabase")
data <- sqlExecute(connHandle, "SELECT * FROM myTable WHERE column = ?", 'myValue', fetch = TRUE)
odbcClose(connHandle)
Documentation is here: https://cran.r-project.org/web/packages/RODBCext/vignettes/Parameterized_SQL_queries.html
More discussion here: Parameterized queries with RODBC

i got the correct way as follows:
query<- paste0("SELECT [Row_Id],[Script_id],[value] FROM
[RiskDashboard].[dbo]. [tbl_Simulation] where Row_Id='",row_id[c(i),],"'
AND Script_Id='",script_id[c(i),],"'")

Related

How does the question mark function in the SQL query?

I'm attempting to edit an ETL package(SSIS) that queries a SQL table and outputs csv files for every StationID and I'm having trouble understanding how the question mark is being used in the query definition below. I understand ? is used a parameter but I don't understand how it's used in the date function below:
SELECT TimeSeriesIdentifier, StationID, ParameterID FROM dbo.EtlView WHERE
LastModified > DATEADD(hour, ?*-1, GETDATE())
AND StationID LIKE
CASE WHEN ? = 0 THEN
StationID
ELSE
?
END
The parameterization available in SSIS is dependent upon the connection manager used.
OLE DB and ODBC based connection managers use ? as the variable place holder, whereas ADO.NET uses a named parameter, #myVariable.
OLE DB begins counting at 0 whereas ODBC used a 1 based counting system. They are both however ordinal based systems so in your CASE expression the two ? are for the same variable. But, you'll have to list that SSIS Variable twice in the parameter mapping dialog because it's ordinal based - i.e. (param, name) => #HoursBack, 0; #MyVar, 1; and #MyVar, 2;
A "dumb trick" I would employ if I had to deal with repeated ordinal based parameters or if I was troubleshooting packages is to make the supplied query use local variables in the query itself.
DECLARE
#HoursBack int = ?
, #MyVariable int = ?;
SELECT
TimeSeriesIdentifier
, StationID
, ParameterID
FROM
dbo.EtlView
WHERE
LastModified > DATEADD(HOUR, #HoursBack * -1, GETDATE())
AND StationID LIKE
CASE
WHEN #MyVariable = 0 THEN StationID
ELSE #MyVariable
END;
Now I only have to map the SSIS Variable #MyVar once into my script as the "normal" TSQL parameterization takes over. The other benefit is that I can copy and paste that into a query tool and sub in the ?s with actual values to inspect the results directly from the source. This can be helpful if you're running into situations where the strong typing in SSIS prevents you from getting the results into a data viewer.
SSIS is building a parameterized query.
You can get more information about this here (MySQL-specific):
What is the question mark's significance in MySQL at "WHERE column = ?"?
Or you can get a more generally-applicable response here: What does a question mark represent in SQL queries?
At a very "nuts and bolts" level, those are parameters being passed into the SQL statement by the package. With the Execute SQL task open, click on the tab that says Parameter Mapping. There will be a list of variables that are being sent into the query, and they are consumed in the order that they're listed.
Here's a logger for an archiving package I'm working on:
The query on the General tab just writes those five values to a table:
INSERT INTO dbo.ArchiveRowCounts (
TableName,
ServerName,
ReportYear,
BaseTblCnt,
ArchiveTblCnt)
VALUES (?,?,?,?,?);

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 Linked Server Example Query

While in Management Studio, I am trying to run a query/do a join between two linked servers.
Is this a correct syntax using linked db servers:
select foo.id
from databaseserver1.db1.table1 foo,
databaseserver2.db1.table1 bar
where foo.name=bar.name
Basically, do you just preface the db server name to the db.table ?
The format should probably be:
<server>.<database>.<schema>.<table>
For example:
DatabaseServer1.db1.dbo.table1
Update: I know this is an old question and the answer I have is correct; however, I think any one else stumbling upon this should know a few things.
Namely, when querying against a linked server in a join situation the ENTIRE table from the linked server will likely be downloaded to the server the query is executing from in order to do the join operation. In the OP's case, both table1 from DB1 and table1 from DB2 will be transferred in their entirety to the server executing the query, presumably named DB3.
If you have large tables, this may result in an operation that takes a long time to execute. After all it is now constrained by network traffic speeds which is orders of magnitude slower than memory or even disk transfer speeds.
If possible, perform a single query against the remote server, without joining to a local table, to pull the data you need into a temp table. Then query off of that.
If that's not possible then you need to look at the various things that would cause SQL server to have to load the entire table locally. For example using GETDATE() or even certain joins. Others performance killers include not giving appropriate rights.
See http://thomaslarock.com/2013/05/top-3-performance-killers-for-linked-server-queries/ for some more info.
SELECT * FROM OPENQUERY([SERVER_NAME], 'SELECT * FROM DATABASE_NAME..TABLENAME')
This may help you.
For those having trouble with these other answers , try OPENQUERY
Example:
SELECT * FROM OPENQUERY([LinkedServer], 'select * from [DBName].[schema].[tablename]')
If you still find issue with <server>.<database>.<schema>.<table>
Enclose server name in []
You need to specify the schema/owner (dbo by default) as part of the reference. Also, it would be preferable to use the newer (ANSI-92) join style.
select foo.id
from databaseserver1.db1.dbo.table1 foo
inner join databaseserver2.db1.dbo.table1 bar
on foo.name = bar.name
select * from [Server].[database].[schema].[tablename]
This is the correct way to call.
Be sure to verify that the servers are linked before executing the query!
To check for linked servers call:
EXEC sys.sp_linkedservers
right click on a table and click script table as select
select name from drsql01.test.dbo.employee
drslq01 is servernmae --linked serer
test is database name
dbo is schema -default schema
employee is table name
I hope it helps to understand, how to execute query for linked server
Usually direct queries should not be used in case of linked server because it heavily use temp database of SQL server. At first step data is retrieved into temp DB then filtering occur. There are many threads about this. It is better to use open OPENQUERY because it passes SQL to the source linked server and then it return filtered results e.g.
SELECT *
FROM OPENQUERY(Linked_Server_Name , 'select * from TableName where ID = 500')
For what it's worth, I found the following syntax to work the best:
SELECT * FROM [LINKED_SERVER]...[TABLE]
I couldn't get the recommendations of others to work, using the database name. Additionally, this data source has no schema.
In sql-server(local) there are two ways to query data from a linked server(remote).
Distributed query (four part notation):
Might not work with all remote servers. If your remote server is MySQL then distributed query will not work.
Filters and joins might not work efficiently. If you have a simple query with WHERE clause, sql-server(local) might first fetch entire table from the remote server and then apply the WHERE clause locally. In case of large tables this is very inefficient since a lot of data will be moved from remote to local. However this is not always the case. If the local server has access to remote server's table statistics then it might be as efficient as using openquery More details
On the positive side T-SQL syntax will work.
SELECT * FROM [SERVER_NAME].[DATABASE_NAME].[SCHEMA_NAME].[TABLE_NAME]
OPENQUERY
This is basically a pass-through. The query is fully processed on the remote server thus will make use of index or any optimization on the remote server. Effectively reducing the amount of data transferred from the remote to local sql-server.
Minor drawback of this approach is that T-SQL syntax will not work if the remote server is anything other than sql-server.
SELECT * FROM OPENQUERY([SERVER_NAME], 'SELECT * FROM DATABASE_NAME.SCHEMA_NAME.TABLENAME')
Overall OPENQUERY seems like a much better option to use in majority of the cases.
I have done to find out the data type in the table at link_server using openquery and the results were successful.
SELECT * FROM OPENQUERY (LINKSERVERNAME, '
SELECT DATA_TYPE, COLUMN_NAME
FROM [DATABASENAME].INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_NAME =''TABLENAME''
')
Its work for me
Following Query is work best.
Try this Query:
SELECT * FROM OPENQUERY([LINKED_SERVER_NAME], 'SELECT * FROM [DATABASE_NAME].[SCHEMA].[TABLE_NAME]')
It Very helps to link MySQL to MS SQL
PostgreSQL:
You must provide a database name in the Data Source DSN.
Run Management Studio as Administrator
You must omit the DBName from the query:
SELECT * FROM OPENQUERY([LinkedServer], 'select * from schema."tablename"')
For MariaDB (and so probably MySQL), attempting to specify the schema using the three-dot syntax did not work, resulting in the error "invalid use of schema or catalog". The following solution worked:
In SSMS, go to Server Objects > Linked Servers > Providers > MSDASQL
Ensure that "Dynamic parameter", "Level zero only", and "Allow inprocess" are all checked
You can then query any schema and table using the following syntax:
SELECT TOP 10 *
FROM LinkedServerName...[SchemaName.TableName]
Source: SELECT * FROM MySQL Linked Server using SQL Server without OpenQuery
Have you tried adding " around the first name?
like:
select foo.id
from "databaseserver1".db1.table1 foo,
"databaseserver2".db1.table1 bar
where foo.name=bar.name

SQL Server: Select in vs or?

Which is faster?
SELECT UserName
FROM dbo.UserTable
WHERE UserID in (1,3,4)
SELECT UserName
FROM dbo.UserTable
WHERE UserID = 1
OR UserID = 3
OR UserID = 4
Due to Sql Server's optimization of queries these will run at the same speed since they are logically equivalent.
i favor the IN syntax for brevity and readability though.
Actually it is the same.
If you display the estimated execution plan you will see that it is performing the same action.
This is relevant when it comes to producing SQL via Linq. There are some instances where the sql created is in the form of: field='xxx' OR field='yyy'.

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