Return the Data from Column Using PowerShell - sql

When I export the $dt to a CSV - it shows in 1.A of Excel = 1 and in 2.A = 2. I need to extract the two value of the second row in column A. First why is the count working? And why do I not get a return for the values in the last two echo commands when I know there is a value = 2 in Row#2 - Column A?
$factory = [System.Data.Common.DbProviderFactories]::GetFactory('IBM.Data.DB2')
$cstrbld = $factory.CreateConnectionStringBuilder()
$cstrbld.Database = 'mydb'
$cstrbld.UserID = 'user'
$cstrbld.Password = 'userpass'
$cstrbld.Server = 'server:port#'
$dbconn = $factory.CreateConnection()
$dbconn.ConnectionString = $cstrbld.ConnectionString
$dbconn.Open()
$dbcmd = $dbconn.CreateCommand()
$dbcmd.CommandText = 'SELECT COUNT(*) FROM dbname.UNIT WHERE STATUS = 3'
$rdr = $dbcmd.ExecuteReader()
$dt = New-Object System.Data.DataTable
$dt.Load($rdr)
$dbconn.Close()
echo $dt.rows.count
## Returns 1
echo $dt.rows[1]
## Returns nothing
echo $dt.rows[1].column0
## Returns nothing
code ```

because index start to 0, try this:
$dt.rows[0]
$dt.Rows[0].ItemArray[0].ToString()

Related

Cannot update SQL Boolean value

For my toggle of a Boolean value with Flask and SQLite I want to change 1 into 0 and 0 into 1 on table engineering_project. The message can be successfully flashed so the if function is working. However, the value of engg_proj_status in the table cannot be updated:
conn = sqlite3.connect(db_path)
conn.row_factory = sqlite3.Row
c = conn.cursor()
c.execute("SELECT engg_proj_status FROM engineering_project WHERE engg_proj_id =?",(engg_proj_id,))
status = c.fetchone()[0]
if status == 1:
c.execute("UPDATE engineering_project SET engg_proj_status = ? WHERE engg_proj_id = ?;",(False,engg_proj_id))
flash("Status changed from COMPLETED to OPEN")
else:
c.execute("UPDATE engineering_project SET engg_proj_status = ? WHERE engg_proj_id = ?;",(True,engg_proj_id))
flash("Status changed from OPEN to COMPLETED")
Add conn.commit()
Thanks to this comment from forpas.

How to assign notification to work order through BAPI?

I would like to assign a notification to a work order. The following does not work:
* Fill method structure
ls_methods-refnumber = 1.
ls_methods-method = 'SAVE'.
APPEND ls_methods TO lt_methods.
ls_methods-refnumber = 1.
ls_methods-objecttype = 'OBJECTLIST'.
ls_methods-method = 'CHANGE'.
ls_methods-objectkey = '000480000020'.
APPEND ls_methods TO lt_methods.
ls_methods-refnumber = 1.
ls_methods-objecttype = 'HEADER'.
ls_methods-method = 'CHANGE'.
ls_methods-objectkey = '000480000020'.
APPEND ls_methods TO lt_methods.
* Fill header structure
ls_header-orderid = '000480000020'.
ls_header-notif_no = '100000356980'.
APPEND ls_header TO lt_header.
* Fill header up structure
ls_header_up-orderid = '000480000020'.
ls_header_up-notif_no = '100000356980' .
APPEND ls_header_up TO lt_header_up.
* Fill object list structure
ls_object_list-notif_no = '100000356980'.
APPEND ls_object_list TO lt_object_list.
* Fill object list up structure
ls_object_list_up-processing_ind = 'X'.
APPEND ls_object_list_up TO lt_object_list_up.
CALL FUNCTION 'BAPI_ALM_ORDER_MAINTAIN'
TABLES
it_methods = lt_methods
it_header = lt_header
it_header_up = lt_header_up
it_objectlist = lt_object_list
it_objectlist_up = lt_object_list_up
return = lt_return .
For OBJECTLIST I would actually need something like an 'ADD' method. Any ideas are appreciated.
The following works for me:
ls_methods-refnumber = 1.
ls_methods-objecttype = 'OBJECTLIST'.
ls_methods-method = 'CREATE'.
ls_methods-objectkey = '000480000020'.
APPEND ls_methods TO lt_methods.
* Fill method structure
ls_methods-refnumber = 1.
ls_methods-method = 'SAVE'.
ls_methods-objecttype = ''.
ls_methods-objectkey = '000480000020'.
APPEND ls_methods TO lt_methods.
* Fill object list structure
ls_object_list-notif_no = '100000356980'.
APPEND ls_object_list TO lt_object_list.
* Fill object list up structure
ls_object_list_up-processing_ind = 'X'.
APPEND ls_object_list_up TO lt_object_list_up.
CALL FUNCTION 'BAPI_ALM_ORDER_MAINTAIN'
TABLES
it_methods = lt_methods
it_objectlist = lt_object_list
it_objectlist_up = lt_object_list_up
return = lt_return.

Getting Error:Table variables and insert 'fieldnames' do not match. while exporting data from matlab to sql

I am getting the Error using database.jdbc.connection/fastinsert (line 140)
Table variables and insert 'fieldnames' do not match. error while exporting data from matlab to sql. Can you please help me out.
Below is my code.
conn = database('rScenariosDB','NCAT\aabhaler','','Vendor','Microsoft SQL Server','Server','A0030110GB6S942','AuthType','Windows','portnumber',1433);
for i = 1 : rScenarioCnt
if rScenario{i}.status == 1
ECostMax(i) = rScenario{i}.ECostMax;
CO2EmisMax(i) = rScenario{i}.CO2EmisMax;
ECost(i) = rScenario{i}.YearAlloc.ECost;
CO2Emis(i) = rScenario{i}.YearAlloc.CO2Emis ;
EmisCostYear(i) = rScenario{i}.YearAlloc.EmisCostYear ;
CO2EmisYear(i) = sum(rScenario{i}.YearAlloc.CO2EmisYear);
end
end
rId = 1 : rScenarioCnt ;
colnames={'rScenarioId' ,'ECostMax' , ' CO2EmisMax','ECost' ,'CO2Emis', 'EmisCostYear', 'CO2EmisYear' };
data = table(rId',ECostMax',CO2EmisMax',ECost',CO2Emis',EmisCostYear', CO2EmisYear','VariableNames',colnames);
tablename = 'rScenarios';
fastinsert(conn,tablename,colnames,data);
curs=exec(conn,'select * from [dbo].[rScenarios]');
curs=fetch(curs);
disp(curs.Data);
close(curs);
close(conn);

Copy multiple tables result to Excel

I have a massive SQL query that returns 4 tables. I'm able to return the first table but not the other tables here is the code I'm using below. I'm using a powershell script that I found online. I was about to get the second table by changing $DataSetTable = $DataSet.Tables[0] to $DataSetTable = $DataSet.Tables[1] the second table was return in the excel sheet but not the first one.
How can I all the tables?
$SQLServer = 'SQLCL01'
$Database = 'home'
$SqlQuery = #' Query goes here'#
## - Connect to SQL Server using non-SMO class 'System.Data':
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $Database; Integrated Security = True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection
## - Extract and build the SQL data object '$DataSetTable':
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$DataSetTable = $DataSet.Tables[0]
## --------- Working with Excel ------- ##
## - Create an Excel Application instance:
$xlsObj = New-Object -ComObject Excel.Application
## - Create new Workbook and Sheet (Visible = 1 / 0 not visible)
$xlsObj.Visible = 1
$xlsWb = $xlsobj.Workbooks.Add()
$xlsSh = $xlsWb.Worksheets.item(1)
$xlsSh = $xlsWb.Worksheets.Item("Sheet1")
$xlsSh.Name = "Back date dump"
$xlsSh = $xlsWb.ActiveSheet
## - Build the Excel column heading:
[Array] $getColumnNames = $DataSetTable.Columns | Select ColumnName
## - Build column header:
[int] $RowHeader = 1
foreach ($ColH in $getColumnNames) {
$xlsSh.Cells.item(1, $RowHeader).font.bold = $true
$xlsSh.Cells.item(1, $RowHeader) = $ColH.ColumnName
$RowHeader++
}
## - Adding the data start in row 2 column 1:
[int] $rowData = 2
[int] $colData = 1
foreach ($rec in $DataSetTable.Rows) {
foreach ($Coln in $getColumnNames) {
## - Next line convert cell to be text only:
$xlsSh.Cells.NumberFormat = "#"
## - Populating columns:
$xlsSh.Cells.Item($rowData, $colData) = $rec.$($Coln.ColumnName).ToString()
$ColData++
}
$rowData++; $ColData = 1
}
## - Adjusting columns in the Excel sheet:
$xlsRng = $xlsSH.usedRange
$xlsRng.EntireColumn.AutoFit()
Loop over all tables in the collection:
$xlsObj = New-Object -ComObject Excel.Application
foreach ($DataSetTable in $DataSet.Tables) {
...
}

SQL: Update does not affect any row

I want to update a dataset in a DB2/AS400 table.
The problem is if I there is string parameter in the parameters list the command does not find a row to update.
For example: If I run the command only with the company number the command will succeed. If I run the command with the company number and facility number the command fails.
Does anyone have any idea?
IDbConnection cn = Tools.GetCnApp();
try
{
StringBuilder sql = new StringBuilder();
sql.AppendLine("UPDATE " + Tools.GetSchemeApp() + "/ChangeReasonAssignments");
sql.AppendLine(" SET Confirmed = #CONF, Confirmed_By = #CONFBY, Confirmed_At = #CONFAT");
sql.AppendLine(" WHERE Company = #CONO AND Facility = #FACI AND Department = #DEPT");
sql.AppendLine(" AND Production_Group = #PRGR AND Manufacturing_Order = #ORDR AND Order_Operation = #OPER");
sql.AppendLine(" AND Confirmed = 0");
IDbCommand cmd = cn.CreateCommand();
cmd.SetParameter("#CONO", this.CompanyNumber);
cmd.SetParameter("#FACI", this.FacilityNumber);
cmd.SetParameter("#DEPT", this.ProductionGroup.Department.Name);
cmd.SetParameter("#PRGR", this.ProductionGroup.Name);
cmd.SetParameter("#ORDR", this.ManufacturingNumber);
cmd.SetParameter("#OPER", this.OperationNumber);
cmd.SetParameter("#CONFBY", Base.User);
cmd.SetParameter("#CONFAT", DateTime.Now.ToString());
cmd.SetParameter("#CONF", 1);
cmd.CommandText = sql.ToString();
if (cmd.ExecuteNonQuery() > 0)
{
}
EDIT
The datatypes in database are:
Company: INTEGER
Facility: VARCHAR
Dpartment: VARCHAR
Production_Group: VARCHAR
Manufacturing_Order:INTEGER
Order_Operation: INTEGER
The datatypes in .NET are:
CompanyNumber: int
FacilityNumber: String
Departmentname: String
ProductionGroup: String
Manufacturingorder: int
OrderOperation: int
sql.ToString() results:
UPDATE TSAEDBDEV/ChangeReasonAssignments SET Confirmed = #CONF, Confirmed_By = #CONFBY, Confirmed_At = #CONFAT WHERE Company = #CONO AND Facility = #FACI AND Confirmed = 0
Try to set the string values into ': cmd.SetParameter("#DEPT", "'" + this.ProductionGroup.Department.Name + "'");