I am trying to use GO to get R to pull a multipart query from a SQL Server database but R keeps erroring out on me when I try this. Does anyone know a workaround to get RODBC to run multipart queries?
Example query:
query2 = "IF OBJECT_ID('tempdb..#ATTTempTable') IS NOT NULL
DROP TABLE #ATTTempTable
GO
SELECT
* INTO #ATTTempTable
FROM ETL.ATT.fact_responses fr
WHERE fr.ResponseDateTime > '2015-07-06'
"
channel <- odbcConnect("<host name>", uid="<uid>", pwd="<pwd>")
raw = sqlQuery(channel, query2)
close(channel)
and result
> raw
[1] "42000 102 [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Incorrect syntax near 'GO'."
[2] "[RODBC] ERROR: Could not SQLExecDirect 'IF OBJECT_ID('tempdb..#ATTTempTable') IS NOT NULL\n DROP TABLE #ATTTempTable\n\nGO\n\nSELECT\n\t* INTO #ATTTempTable\nFROM ETL.ATT.fact_responses fr\nWHERE fr.ResponseDateTime > '2015-07-06'\n'"
>
Because your query contains multiple line with conditional logic it resembles a stored procedure.
Simply save that stored procedure in SQL Server:
CREATE PROCEDURE sqlServerSp #ResponseDateTime nvarchar(10)
AS
IF OBJECT_ID('tempdb..#ATTTempTable') IS NOT NULL
DROP TABLE #ATTTempTable;
GO
-- suppresses affected rows message so RODBC returns a dataset
SET NO COUNT ON;
GO
-- runs make-table action query
SELECT * INTO #ATTTempTable
FROM ETL.ATT.fact_responses fr
WHERE fr.ResponseDateTime > #ResponseDateTime;
GO
And then run the stored procedure in R. You can even pass parameters like the date:
channel <- odbcConnect("<host name>", uid="<uid>", pwd="<pwd>")
raw = sqlQuery(channel, "EXEC sqlServerSp #ResponseDateTime='2015-07-06'")
close(channel)
You can't. See https://msdn.microsoft.com/en-us/library/ms188037.aspx
you have to divide your query into two statements and run them separately.
Related
Using the robot-framework to connect with Sybase DB
Then DELETE row, UPDATE row in a TABLE.
When the below query is executed in robot framework, it works fine.
Sybase DB Connection - Delete and Update for a single pass
connect To Database Using Custom Params pyodbc "Driver={Adaptive Server Enterprise}; server=<myserver>; port=<myport>;db=<mydb>;uid=<myuser>; pwd=<mypasswd>;"
# Run Select Query
#{selectQuery} Query select * from TABLE where FIELD1 = '1000'
Log Many #{selectQuery}
Log "Selected Query Executed"
# Run Delete Query
#{DeleteQuery} Execute Sql String set chained off ; Delete from TABLE where FIELD1 = '1000' AND FIELD2 = 'VALUE2' AND FIELD3 = 'VALUE3'
Log Many #{DeleteQuery}
Log "Delete Query Executed"
#Run Update Query
#{updateQuery} Execute Sql String set chained off ; UPDATE TABLE SET FIELD2 = 'VALUE2' where FIELD1 = '1001'
Log Many #{updateQuery}
Log "Update Query Executed"
Disconnect From Database
Whereas when the for loop is used as below :
Sybase DB Connection - Delete with for loop for mutliple passes
connect To Database Using Custom Params pyodbc "Driver={Adaptive Server Enterprise}; server=<myserver>; port=<myport>;db=<mydb>;uid=<myuser>; pwd=<mypasswd>;"
#Run DELETE Query
:FOR ${num} IN RANGE 100
\ Execute Sql String set chained off ; Delete from TABLE where FIELD1 = ${num} and FIELD2= "${VALUE2[${num}]}" and FIELD3 = "${VALUE3[${num}]}"
\ sleep 1
It fails with the below error :
[Sybase][ODBC Driver][Adaptive Server Enterprise]SET CHAINED command not allowed within multi-statement transaction.\n (226) (SQLExecDirectW);
[Sybase][ODBC Driver][Adaptive Server Enterprise]Stored procedure 'abc_sp' may be run only in unchained transaction mode. The 'SET CHAINED OFF' command will cause the current session to use unchained transaction mode.\n (7713)")
Used the commit
The below for loop worked fine.
connect To Database Using Custom Params pyodbc "Driver={Adaptive Server Enterprise}; server=<myserver>; port=<myport>;db=<mydb>;uid=<myuser>; pwd=<mypasswd>;"
#Run DELETE Query
:FOR ${num} IN RANGE 100
\ Execute Sql String commit
\ Execute Sql String set chained off ; Delete from TABLE where FIELD1 = ${num} and FIELD2= "${VALUE2[${num}]}" and FIELD3 = "${VALUE3[${num}]}"
\ Execute Sql String commit
I am creating a WPF application using Advantage database server. I want to insert some data using stored procedure
Any sample code ?
I tried two input parameter TestID and TestName (both NCHAR)
INSERT INTO TestTable(
Test_Id,
Test_Name)
VALUES (
#TestID,
#TestName);
But show error like
Error 7200: AQE Error: State = HY000; NativeError = 5154;
[SAP][Advantage SQL Engine][ASA] Error 5154: Execution of the stored
procedure failed. Procedure Name: TestInsert. Error 7200: AQE
Error: State = S0000; NativeError = 2121; [SAP][Advantage SQL
Engine]Column not found: #TestID -- Location of error in the SQL
statement is: 42 (line: 3 column: 5) Error in stored procedure:
TestInsert AdsCommand query execution failed.
I am new in SAP ADS. Please help me.
use _XXXX notation for input parameters.
ie,
INSERT INTO TestTable( Test_Id, Test_Name)
VALUES ( _#TestID, _#TestName);
Using BizTalk I am trying to insert/update the table in the SQL Server database using the stored procedure. I have created a stored procedure and the Table Type like below
CREATE TYPE dbo.dept_TT AS TABLE
(
dept_name varchar(64),
jax_dept_id char(32)
)
GO
CREATE PROCEDURE [dbo].[uspInsertorUpdateDept]
#dept_TT dept_TT READONLY
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRANSACTION;
UPDATE dep
SET dep.dept_name = dtt.dept_name,
dep.jax_dept_id = dtt.jax_dept_id
FROM [afm].[jax_dept] dep
INNER JOIN #dept_TT dtt ON dep.jax_dept_id = dtt.jax_dept_id
INSERT INTO [afm].[jax_dept](dept_name, jax_dept_id )
SELECT dtt.dept_name, dtt.jax_dept_id
FROM #dept_TT dtt
WHERE NOT EXISTS (SELECT 1
FROM [afm].[jax_dept]
WHERE jax_dept_id = dtt.jax_dept_id)
COMMIT TRANSACTION;
END;
When I execute the stored produre in the SQL Server management studio it insert/updates the records as expected. I am consuming this storedprocedure in the biztalk application and tried to run the application it throws error like
The adapter failed to transmit message going to send port "WcfSendPort_SqlAdapterBinding_Procedures_dbo_Custom_Dep" with URL "mssql://". It will be retransmitted after the retry interval specified for this Send Port. Details:"Microsoft.ServiceModel.Channels.Common.XmlReaderParsingException: An unexpected method call was made. Ensure that the XML is well formed. The stack trace of the method call was : Void WriteFullEndElement().
I enabled the tracking and tried seeing the XML that is sent to the send port and it looks good like below.
<?xml version="1.0" encoding="utf-8"?>
<ns0:uspInsertorUpdateDept xmlns:ns0="http://schemas.microsoft.com/Sql/2008/05/Procedures/dbo" xmlns:ns4="http://schemas.datacontract.org/2004/07/System.Data" xmlns:ns3="http://schemas.microsoft.com/Sql/2008/05/Types/TableTypes/dbo" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ns0:dept_TT>
<ns3:dept_TT>
<ns3:dept_name>lab1</ns3:dept_name>
<ns3:jax_dept_id>RRI</ns3:jax_dept_id>
</ns3:dept_TT>
<ns3:dept_TT>
<ns3:dept_name>lab2</ns3:dept_name>
<ns3:jax_dept_id>RAFAC</ns3:jax_dept_id>
</ns3:dept_TT>
</ns0:dept_TT>
</ns0:uspInsertorUpdateDept>
Xml generated for the stored procedure in the VS
<ns0:uspInsertorUpdateDept xmlns:ns0="http://schemas.microsoft.com/Sql/2008/05/Procedures/dbo">
<ns0:dept_TT>
<ns1:dept_TT xmlns:ns1="http://schemas.microsoft.com/Sql/2008/05/Types/TableTypes/dbo">
<ns1:dept_name>dept_namedept_namedept_namedept_namedept_namedept_namedept_named</ns1:dept_name>
<ns1:jax_dept_id>jax_dept_idjax_dept_idjax_dept_i</ns1:jax_dept_id>
</ns1:dept_TT>
<ns1:dept_TT xmlns:ns1="http://schemas.microsoft.com/Sql/2008/05/Types/TableTypes/dbo">\
<ns1:dept_name>dept_namedept_namedept_namedept_namedept_namedept_namedept_named</ns1:dept_name>
<ns1:jax_dept_id>jax_dept_idjax_dept_idjax_dept_i</ns1:jax_dept_id>
</ns1:dept_TT>
<ns1:dept_TT xmlns:ns1="http://schemas.microsoft.com/Sql/2008/05/Types/TableTypes/dbo">
<ns1:dept_name>dept_namedept_namedept_namedept_namedept_namedept_namedept_named</ns1:dept_name>
<ns1:jax_dept_id>jax_dept_idjax_dept_idjax_dept_i</ns1:jax_dept_id>
</ns1:dept_TT>
</ns0:dept_TT>
</ns0:uspInsertorUpdateDept>
Not sure what am I missing here. Any help is greatly appreciated
I've copied an SQL code that I've previously tried in SQL Server manager and that was working with SQL Server Manager.
In QlikView I get "ErrorSource: (null), ErrorMsg: (null)"
What could be the mistake? I'm using a temp table (#Clasif1) because in the original script I have multiple Insert Into Commands.
Thanks!!
LOAD *;
SQL INSERT INTO #Clasif1
SELECT de.pate_tempor, de.prod_codigo, de.liqu_numero,
concepto = Convert(char(50),'FOB Fruta Exportacion'),
kilos = Convert(decimal(14,2),SUM(de.dece_kilrea)),
total_plata = Convert(decimal(14,2),sum((de.dece_kilrea/de.enva_pesone)*de.dece_fobuni))
FROM dba.detacajemb de
WHERE de.pate_tempor = 2015
and de.pool_tipool = 1
GROUP BY de.pate_tempor, de.prod_codigo, de.liqu_numero
SELECT cla.pate_tempor, cla.prod_codigo, cla.concepto, cla.kilos, cla.total_plata, cla.liqu_numero
FROM #Clasif1 cla;
You cannot perform an INSERT command from QV. You can create a stored procedure that runs your code above and call that.
SQL exec stored_procedure <parameters>
I'm trying to run the following UPDATE query from a python script (note I've removed the database info):
print 'Connecting to db for update query...'
db = pyodbc.connect('DRIVER={FreeTDS};SERVER=<removed>;DATABASE=<removed>;UID=<removed>;PWD=<removed>')
cursor = db.cursor()
print ' Executing SQL queries...'
for i in range(len(data)):
sql = '''
UPDATE product.sanction
SET action_summary = '{action_summary}'
WHERE sanction_id = {sanction_id};
'''.format(sanction_id=data[i][0], action_summary=data[i][1])
cursor.execute(sql)
cursor.close()
db.commit()
db.close()
However, it hangs indefinitely, no error.
I'm new to pyodbc, but it should be setup correctly considering I'm having no problems performing SELECT queries. I did have to call CAST for SELECT queries (I've cast sanction_id AS INT [int identity on the database] and action_summary AS TEXT [nvarchar on the database]) to properly populate data, so perhaps the problem lies somewhere there, but I don't know where to start debugging. Converting the text to NVARCHAR didn't do anything either.
Here's an example of one of the rows in data:
(2861357, 'Exclusion Program: NonProcurement; Excluding Agency: HHS; CT Code: Z; Exclusion Type: Prohibition/Restriction; SAM Number: S4MR3Q9FL;')
I was unable to find my issue, but I ended up using QuerySets rather than running an UPDATE query.