Station = SN[0]
Asset = AN[0]
y = ASD[0]
z = ACD[0]
cursor = conn.cursor()
cursor.execute('SELECT * FROM station')
cursor.execute('''
UPDATE station
SET ActualStartDate = y, ActualCompletionDate = z
WHERE StationName = #Station and AssetNumber = #Asset
''')
conn.commit()
I am getting this error:
('42000', '[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Must declare the scalar variable "#Station". (137) (SQLExecDirectW)')
I would like to get the values from 4 numpy arrays above, SN[0], AN[0], SCD[0] SSD[0] and use these values in the UPDATE Query.
Is it possible to execute this?
As noted in the pyodbc documentation, your parameter placeholders must be question marks and you must pass the parameter values along with the SQL command text in the .execute() call:
sql = """\
UPDATE station
SET ActualStartDate = ?, ActualCompletionDate = ?
WHERE StationName = ? and AssetNumber = ?
"""
params = (y, z, Station, Asset)
cursor.execute(sql, params)
Related
I need to execute a procedure from python as below
DECLARE
#LayoutID INT = 9
,#PrivateFL INT =0
,#FromDate DATETIME = '20100101'
,#ToDate DATETIME = '20211001'
,#VesselIDs dbo.UniqueIntList
insert into #VesselIDs values (202),(330)
EXEC usp_GetComments #LayoutID, #PrivateFL, #FromDate, #ToDate, #VesselIDs
How do i pass '#VesselIDs' as parameter while executing it using python?
I tried below but its not working
list = [202,330]
storedProc = "EXEC usp_GetComments #LayoutID=?, #PrivateFL=?, #FromDate=?, #ToDate=?,
#VesselIDs=?"
params = (9,0,'20100101','20211001',list)
Do as below:
storedProc = "EXEC usp_GetComments #LayoutID=?, #PrivateFL=?, #FromDate=?, #ToDate=?, #VesselIDs=?"
fktvp = [(202,),(330,)]
fkparams = (9,0,'20100101','20211001',fktvp)
cursor.execute( storedProc, fkparams )
I am trying to assign a simple sql query result in stored procedure to a variable which I will use it later in another sql statement. If I execute below statement with out putting in procedure it works but not with stored procedure, I get an error while calling sp , Can someone please help me here ?
Procedure code:
$$
VAR NAME = 'ABC'
SET (COUNT_VALUE) = (SELECT COUNT(*) FROM COUNT_TABLE)
With out Procedure below code works
SET (COUNT_VALUE) = (SELECT COUNT(*) FROM COUNT_TABLE)
select $COUNT_VALUE
Thanks
Here's an example that uses a simple helper function to return a result set from a query. You can read the Snowflake docs to see what the result set API has in it. The getResultSet function returns a variable that has the results of the query. Since the SQL is a count, you need to use rs.next() once to get to the first row and then read the value in the aliased count(*). You could also use rs.getColumnValue(1) to get a column by ordinal position, but I recommend using column names with SQL aliases is necessary.
create or replace procedure COUNT_EXAMPLE()
returns string
language javascript
as
$$
var rowCount = 0;
var sql = "select count(*) as ROW_COUNT from SNOWFLAKE_SAMPLE_DATA.TPCH_SF10000.ORDERS;";
try {
var rs = getResultSet(sql);
if (rs.next()) {
var rowCount = rs.getColumnValue("ROW_COUNT");
} else {
return "Error: Count query failed.";
}
}
catch(err) {
return "Error: " + err.message;
}
return "The table has " + rowCount + " rows.";
//--------------------------- End of main function ---------------------------
function getResultSet(sql){
cmd1 = {sqlText: sql};
stmt = snowflake.createStatement(cmd1);
var rs;
rs = stmt.execute();
return rs;
}
$$;
call COUNT_EXAMPLE();
The below code tries to connect to a mssql database using pymssql. I have a CSV file and I am trying to push all the rows into a single data table in the mssql database. I am getting a 'KeyError' when I try to execute the code after opening the CSV file.
import csv
import pymssql
conn = pymssql.connect(host="host name",
database="dbname",
user = "username",
password = "password")
cursor = conn.cursor()
if(conn):
print("True")
else:
print("False")
with open ('path to csv file', 'r') as f:
reader = csv.reader(f)
columns = next(reader)
query = "INSERT INTO Marketing({'URL', 'Domain_name', 'Downloadables', 'Text_without_javascript', 'Downloadable_Link'}) VALUES ({%s,%s,%s,%s,%s})"
query = query.format(','.join('[' + x + ']' for x in columns), ','.join('?' * len(columns)))
cursor = conn.cursor()
for data in reader:
cursor.execute(query, tuple(data))
cursor.commit()
The below is the error that I get:
KeyError: "'URL', 'Domain_name', 'Downloadables', 'Text_without_javascript', 'Downloadable_Link'"
Using to_sql
file_path = "path to csv"
engine = create_engine("mssql://user:password#host/database")
df = pd.read_csv(file_path, encoding = 'latin')
df.to_sql(name='Marketing',con=engine,if_exists='append')
Output:
InterfaceError: (pyodbc.InterfaceError) ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')
I tried everything, from converting the parameters which were being passed to a tuple, passing it as is, but didn't help. Below is the code that helped me fix the issue:
with open ('path to csv file', 'r') as f:
for row in f:
reader = csv.reader(f)
# print(reader)
columns = next(reader)
# print(columns)
cursor = conn.cursor()
for data in reader:
# print(data)
data = tuple(data)
# print(data)
query = ("INSERT INTO Marketing(URL, Domain_name, Downloadables, Text_without_javascript, Downloadable_Link) VALUES (%s,%s,%s,%s,%s)")
parameters = data
# query = query.format(','.join('?' * len(columns)))
cursor.execute(query, parameters)
conn.commit()
Note: The connecting to the database part remains as in the question.
I am trying to convert my DB2 stored procedure to SQL Server and I'm not sure about this xmltable function
DECLARE #IN_AR_UTL_DATA_XML XML
DECLARE #WS_ACCOUNT_NO DECIMAL(13,0)
DECLARE #WS_BILL_NO INT
SET #IN_AR_UTL_DATA_XML = '<CUST_CHARGES>
<AC_NO>50001233</AC_NO>
<INVOICE_NO>63877</INVOICE_NO>
<INVOICELINES>
<INVOICELINE>
<INVOICE_ENTITY>V52259108</INVOICE_ENTITY>
<ENTITY_TYPE>W</ENTITY_TYPE>
<REVENUE_CLASS>7811</REVENUE_CLASS>
<SEQUENCE_NO>1</SEQUENCE_NO>
<IS_FIXED>false</IS_FIXED>
<IS_BACKOUT>true</IS_BACKOUT>
<DATE_ORIG_INVOICE>20190801</DATE_ORIG_INVOICE>
<CODE_INVOICE_ITM_TYPE>B</CODE_INVOICE_ITM_TYPE>
<INVOICE_ITEM_TIMESTMP>2018-09-
18T09:36:33.703214</INVOICE_ITEM_TIMESTMP>
<TOTAL_AMOUNT>300.44</TOTAL_AMOUNT>
<CHARGES>
<WATER_CHARGES>0</WATER_CHARGES>
<SEWER_CHARGES>300.44</SEWER_CHARGES>
<WATER_CHARGE>-222.3</WATER_CHARGE>
<SEWER_CHARGE>0</SEWER_CHARGE>
<WATER_REFUND>222.3</WATER_REFUND>
<SEWER_DISCOUNT>300.44</SEWER_DISCOUNT>
<CAP_DISCOUNT>0</CAP_DISCOUNT>
<SUR_CHARGE>0</SUR_CHARGE>
</CHARGES>
</INVOICELINE>
<INVOICELINE>
<INVOICEING_ENTITY>V52259109</INVOICEING_ENTITY>
<ENTITY_TYPE>W</ENTITY_TYPE>
<REVENUE_CLASS>611</REVENUE_CLASS>
<SEQUENCE_NO>2</SEQUENCE_NO>
<IS_FIXED>false</IS_FIXED>
<IS_BACKOUT>false</IS_BACKOUT>
<DATE_ORIG_INVOICE>20180918</DATE_ORIG_INVOICE>
<CODE_INVOICE_ITM_TYPE>C</CODE_INVOICE_ITM_TYPE>
<INVOICE_ITEM_TIMESTMP>2018-09-
18T09:36:34.238839</INVOICE_ITEM_TIMESTMP>
<TOTAL_AMOUNT>-938.21</TOTAL_AMOUNT>
<CHARGES>
<WATER_CHARGES>0</WATER_CHARGES>
<SEWER_CHARGES>-938.21</SEWER_CHARGES>
<WATER_CHARGE>694.2</WATER_CHARGE>
<SEWER_CHARGE>0</SEWER_CHARGE>
<WATER_REFUND>-694.2</WATER_REFUND>
<SEWER_DISCOUNT>-938.21</SEWER_DISCOUNT>
<CAP_DISCOUNT>0</CAP_DISCOUNT>
<SUR_CHARGE>0</SUR_CHARGE>
</CHARGES>
</INVOICELINE>
</INVOICELINES>
</CUST_CHARGES>'
Above is my sample XML code. Below is my DB2 statement that needs to be converted.
SELECT
WS_AC_NO = TABLE1.XmlCol1.value('AC_NO[1]' ,'DECIMAL(13,0)')
,WS_INVOICE_NO = TABLE1.XmlCol1.value('INVOICE_NO[1]','SMALLINT')
--,INVOICE_ENTITY = TABLE1.XmlCol1.value('#INVOICE_ENTITY','VARCHAR(9)') -- This is not working.
,INVOICE_ENTITY = TABLE2.XmlCol2.value('INVOICELINES[1]/INVOICELINE[1]/INVOICE_ENTITY[1]','VARCHAR(9)')
,ENTITY_TYPE = TABLE1.XmlCol1.value('INVOICELINES[1]/INVOICELINE[1]/ENTITY_TYPE[1]' ,'CHAR(1)')
,REVENUE_CLASS = TABLE1.XmlCol1.value('INVOICELINES[1]/INVOICELINE[1]/REVENUE_CLASS[1]' ,'SMALLINT')
,SEQUENCE_NO = TABLE1.XmlCol1.value('INVOICELINES[1]/INVOICELINE[1]/SEQUENCE_NO[1]' ,'SMALLINT')
,TOTAL_AMOUNT = TABLE1.XmlCol1.value('INVOICELINES[1]/INVOICELINE[1]/TOTAL_AMOUNT[1]' ,'DECIMAL(11,2)')
,CHARGE = TABLE1.XmlCol1.value('INVOICELINES[1]/INVOICELINE[1]/XmlCol[1]','DECIMAL(11,2)') -- I need all sub charge values
,'W' AS CHARGE_TYPE
,1 AS ORDER_SEQUENCE_NO
,DATE_ORIG_BILL = TABLE1.XmlCol1.value('INVOICELINES[1]/INVOICELINE[1]/DATE_ORIG_BILL[1]' ,'INT')
,CODE_BILL_ITM_TYPE = TABLE1.XmlCol1.value('INVOICELINES[1]/INVOICELINE[1]/CODE_BILL_ITM_TYPE[1]','VARCHAR(1)')
,BILL_ITEM_TIMESTMP = TABLE1.XmlCol1.value('INVOICELINES[1]/INVOICELINE[1]/BILL_ITEM_TIMESTMP[1]','DATETIME2(6)')
FROM #IN_AR_UTL_DATA_XML.nodes('/CUAT_CHARGES') TABLE1(XmlCol1)
CROSS APPLY #IN_AR_UTL_DATA_XML.nodes('/CUAT_CHARGES/INVOICELINES/INVOICELINE')
TABLE2(XmlCol2)
Can you please share SQL Server equivalent syntax for this? SQL Server version 2014 / 2016 is preferred. Thanks.
Perhaps something like:
DECLARE #IN_AR_UTL_DATA_XML XML
DECLARE #WS_ACCOUNT_NO DECIMAL(13,0)
DECLARE #WS_BILL_NO INT
SET #IN_AR_UTL_DATA_XML = '<CUST_CHARGES>
<AC_NO>50001233</AC_NO>
<INVOICE_NO>63877</INVOICE_NO>
<INVOICELINES>
<INVOICELINE>
<INVOICE_ENTITY>V52259108</INVOICE_ENTITY>
<ENTITY_TYPE>W</ENTITY_TYPE>
<REVENUE_CLASS>7811</REVENUE_CLASS>
<SEQUENCE_NO>1</SEQUENCE_NO>
<IS_FIXED>false</IS_FIXED>
<IS_BACKOUT>true</IS_BACKOUT>
<DATE_ORIG_INVOICE>20190801</DATE_ORIG_INVOICE>
<CODE_INVOICE_ITM_TYPE>B</CODE_INVOICE_ITM_TYPE>
<INVOICE_ITEM_TIMESTMP>2018-09-
18T09:36:33.703214</INVOICE_ITEM_TIMESTMP>
<TOTAL_AMOUNT>300.44</TOTAL_AMOUNT>
<CHARGES>
<WATER_CHARGES>0</WATER_CHARGES>
<SEWER_CHARGES>300.44</SEWER_CHARGES>
<WATER_CHARGE>-222.3</WATER_CHARGE>
<SEWER_CHARGE>0</SEWER_CHARGE>
<WATER_REFUND>222.3</WATER_REFUND>
<SEWER_DISCOUNT>300.44</SEWER_DISCOUNT>
<CAP_DISCOUNT>0</CAP_DISCOUNT>
<SUR_CHARGE>0</SUR_CHARGE>
</CHARGES>
</INVOICELINE>
<INVOICELINE>
<INVOICEING_ENTITY>V52259109</INVOICEING_ENTITY>
<ENTITY_TYPE>W</ENTITY_TYPE>
<REVENUE_CLASS>611</REVENUE_CLASS>
<SEQUENCE_NO>2</SEQUENCE_NO>
<IS_FIXED>false</IS_FIXED>
<IS_BACKOUT>false</IS_BACKOUT>
<DATE_ORIG_INVOICE>20180918</DATE_ORIG_INVOICE>
<CODE_INVOICE_ITM_TYPE>C</CODE_INVOICE_ITM_TYPE>
<INVOICE_ITEM_TIMESTMP>2018-09-
18T09:36:34.238839</INVOICE_ITEM_TIMESTMP>
<TOTAL_AMOUNT>-938.21</TOTAL_AMOUNT>
<CHARGES>
<WATER_CHARGES>0</WATER_CHARGES>
<SEWER_CHARGES>-938.21</SEWER_CHARGES>
<WATER_CHARGE>694.2</WATER_CHARGE>
<SEWER_CHARGE>0</SEWER_CHARGE>
<WATER_REFUND>-694.2</WATER_REFUND>
<SEWER_DISCOUNT>-938.21</SEWER_DISCOUNT>
<CAP_DISCOUNT>0</CAP_DISCOUNT>
<SUR_CHARGE>0</SUR_CHARGE>
</CHARGES>
</INVOICELINE>
</INVOICELINES>
</CUST_CHARGES>'
SELECT
WS_AC_NO = r.chargeNode.value('AC_NO[1]' ,'DECIMAL(13,0)')
,WS_INVOICE_NO = r.chargeNode.value('INVOICE_NO[1]','INT')
,INVOICE_ENTITY = i.lineNode.value('INVOICE_ENTITY[1]','VARCHAR(9)')
,ENTITY_TYPE = i.lineNode.value('ENTITY_TYPE[1]' ,'CHAR(1)')
,REVENUE_CLASS = i.lineNode.value('REVENUE_CLASS[1]' ,'INT')
,SEQUENCE_NO = i.lineNode.value('SEQUENCE_NO[1]' ,'INT')
,TOTAL_AMOUNT = i.lineNode.value('TOTAL_AMOUNT[1]' ,'DECIMAL(11,2)')
,WATER_CHARGES = i.lineNode.value('(CHARGES/WATER_CHARGE)[1]','DECIMAL(11,2)') -- I need all sub charge values
,'W' AS CHARGE_TYPE
,1 AS ORDER_SEQUENCE_NO
FROM #IN_AR_UTL_DATA_XML.nodes('/CUST_CHARGES') r(chargeNode)
CROSS APPLY chargeNode.nodes('INVOICELINES/INVOICELINE') i(lineNode)
I'm trying to select results from a database for each position of a vector using classic ASP and SQL Server. The code so far:
FOR EACH x IN Tabela
sql = "SELECT DISTINCT tborders.family AS family, tborders.qty AS qty, tborders.los AS los, CONVERT(DATE, tborders.mrd_date) AS mrd FROM [DASH].[dashboard_db].[dbo].[tb_family] AS tbfamily INNER JOIN [DASH].[dashboard_db].[dbo].[tb_started_zero] AS tborders ON tbfamily.[family] = tborders.[family] WHERE tborders.[Order Number] = "&x&""
SET rs = conn.execute(sql)
IF rs.EOF = false THEN
mrd(counter) = rs("mrd")
family(counter) = rs("family")
los(counter) = rs("los")
qty(counter) = rs("qty")
counter=counter+1
END IF
NEXT
Taking note that tborders.[Order Number] is a int typed value. For some reason I'm having this error:
Microsoft SQL Server Native Client 11.0 error '80040e14'
Incorrect syntax near '='.
/asplearning/act/validate-schedule-line.asp, line 46
I have tried removing the SET, but then my result set isn't recognized as a object. I'm pretty sure that the types are just fine, I have tried:
if isNumeric(x) THEN
response.write("<h1>it is numeric</h1>")
else
response.write("<h1>not numeric</h1>")
end if
And it has written "it is numeric" for each position of Tabela. Can anyone help with what it seems to be the problem?
It's look you have an empty item (first or last item of the collection).
I strongly suggest you to use sp_executesql. This will use a compiled execution plan, and this will validate your parameters (against sql injection).
FOR EACH x IN Tabela
if len(x) > 0 then
sql = "exec sp_executeSql N'SELECT DISTINCT tborders.family AS family, tborders.qty AS qty, tborders.los AS los, CONVERT(DATE, tborders.mrd_date) AS mrd FROM [DASH].[dashboard_db].[dbo].[tb_family] AS tbfamily INNER JOIN [DASH].[dashboard_db].[dbo].[tb_started_zero] AS tborders ON tbfamily.[family] = tborders.[family] WHERE tborders.[Order Number] = #OrderNumber', N'#OrderNumber int', #orderNumber = " & x
SET rs = conn.execute(sql)
IF rs.EOF = false THEN
mrd(counter) = rs("mrd")
family(counter) = rs("family")
los(counter) = rs("los")
qty(counter) = rs("qty")
counter=counter+1
END IF
rs.close
end if
NEXT