I have an Invoice that I need to move from Pending Sales
to a Sale Journal, at the end of year to a Master Sale Journal.
Old quotes get moved to a Quote Archive as well. Quotes and Invoices
from the Sale Journal can be moved back to Pending Sales.
I want to build a class that I can pass the source and destination tables
to and move the invoice in and out of.
I have never done a Stored Procedure or pass the adapterTable to a procedure
either.
I am not sure what is the best method to approach a seedy solution is.
I am thinking a stored procedure is the way to go, but how to do a Fill and Insert?
Ideas? code examples?
Started playing with this, but not even close to a good sstart
SqlDataAdapter daPASQS = new SqlDataAdapter("SELECT * FROM " + "VF_PasQS" + " WHERE (calendar_year = " + year + ") and (inv_no_ =" +
InvNo + ") and (s = " + Series + "}", pasps);
DataSet dsPASQS = new DataSet();
daPASPR.TableMappings.Add("vf_PASQS", "invNo");
daPASPR.Fill(dsPASQS, "invNo");
BindingSource myBinding = new BindingSource(dsPASQS, "invNo");
pasps.Close();
int invNo = 0;
foreach (DataRow row in dsPASQS.Tables[0].Rows)
{
invNo = (Int32)row["invNo"];
}
Thanks,
Jerry
Been playing with the following,
string str = "select * into VF_PASPS " +
"FROM vf_PASQS " +
"WHERE (calendar_year = '" + year + "') AND (inv_no_ = '" + InvNo + "') AND (s = '" + Series + "')";
but only creats a NEW TABLE. I need to add/append to an existing table
Thanks,
Jerry
You can use the SqlBulkCopy class
Related
I have a task of loading data from a .txt file to SQL Server table using Script Component in SSIS. I have loaded that successfully using a script.
public void Main()
{
//Declare Variables
string SourceFolderPath = Dts.Variables["$Project::Landing_Zone"].Value.ToString();
string FileExtension = Dts.Variables["User::FileExtension"].Value.ToString();
string FileDelimiter = Dts.Variables["User::FileDelimiter"].Value.ToString();
string ArchiveFolder = Dts.Variables["User::ArchiveFolder"].Value.ToString();
string ColumnsDataType = Dts.Variables["User::ColumnsDataType"].Value.ToString();
string SchemaName = Dts.Variables["$Project::SchemaName"].Value.ToString();
//Reading file names one by one
string[] fileEntries = Directory.GetFiles(SourceFolderPath, "*" + FileExtension);
foreach (string fileName in fileEntries)
{
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(Dts.Connections["DBConn"].AcquireConnection(Dts.Transaction) as SqlConnection);
//Writing Data of File Into Table
string TableName = "";
int counter = 0;
string line;
string ColumnList = "";
//MessageBox.Show(fileName);
System.IO.StreamReader SourceFile =
new System.IO.StreamReader(fileName);
while ((line = SourceFile.ReadLine()) != null)
{
if (counter == 0)
{
ColumnList = "[" + line.Replace(FileDelimiter, "],[") + "]";
TableName = (((fileName.Replace(SourceFolderPath, "")).Replace(FileExtension, "")).Replace("\\", ""));
string CreateTableStatement = "IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[" + SchemaName + "].";
CreateTableStatement += "[" + TableName + "]')";
CreateTableStatement += " AND type in (N'U'))DROP TABLE [" + SchemaName + "].";
CreateTableStatement += "[" + TableName + "] Create Table " + SchemaName + ".[" + TableName + "]";
CreateTableStatement += "([" + line.Replace(FileDelimiter, "] " + ColumnsDataType + ",[") + "] " + ColumnsDataType + ")";
SqlCommand CreateTableCmd = new SqlCommand(CreateTableStatement, myADONETConnection);
CreateTableCmd.ExecuteNonQuery();
//MessageBox.Show(CreateTableStatement);
}
else
{
string query = "Insert into " + SchemaName + ".[" + TableName + "] (" + ColumnList + ") ";
query += "VALUES('" + line.Replace(FileDelimiter, "','") + "')";
// MessageBox.Show(query.ToString());
SqlCommand myCommand1 = new SqlCommand(query, myADONETConnection);
myCommand1.ExecuteNonQuery();
}
counter++;
}
SourceFile.Close();
}
}
Package Variable Details
But the problem is that I could load all the values from the text file to the table only with a single data type(I used nvarchar(200) as a common data type for all values). I have passed nvarchar(200) as a value in one of the package variable and I have called that in the script.
I am expecting the script component to assign a DataType to the columns by understanding the values available in the text file.
Example: The text file which I loaded into the table has got the following data.
Id,Name,Age
1,Arun,25
2,Ramesh,26
3,Anish,28
As a result a table with the name dbo.File_1 is created with columns Id, Name and Age. But all the these columns are created with the same datatype nvarchar(200) as mentioned previously.
But my requirement is that the script component should assign data types based on the values, say for example, The Column Id should be assigned with datatype int, Name should be assigned with datatype nvarchar(50) and so on. Likewise the script should assign datatypes based on any kind of values(Like Decimal, Date etc)
Is there any possible way to achieve this? Thanks in advance.
Additional Hint:
This script normally Drop and Create a new table everytime during the execution. The table name is based on the FileName.
This is shooting from the hip on this one, but maybe using tryparse:
col += int.TryParse(ID, out num)? "int" : "nvarchar(200)";
I am having a problem in making a report to show the comparison between present transaction result and its future impact result
i am using vb.net and i am displaying the report using the values in the data table and so far my data table shows record like this.
In this record f_id = 1 in both purchase and sale transaction and it will increment on both if there are more transaction.
I have to display the purchase transaction which has f_id = 1 on the left and other on the right side.Image 3 will tells you what am trying to say
currently my reports are displaying like this
but i want to display the report in this style so that its much more easier to compare between the two.
here is my code that prints the data on the report
Private Sub FutureTransaction()
Dim sql = "SELECT client.cl_cname, company.co_sname, invmast.im_qty, invmast.im_rate, invmast.im_tdate,invmast.im_crate,invmast.im_tax,invmast.f_type,invmast.f_id"
Sql += " FROM invmast "
sql += "INNER JOIN company ON invmast.co_scode = company.co_scode "
sql += "INNER JOIN client ON invmast.cl_ccode = client.cl_ccode and"
sql += " invmast.fn_code = client.fn_code"
sql += " where invmast.im_tdate>='" & dtpFromDate.Value.ToString("dd-MMM-yyyy") & "' and invmast.im_tdate <= '" & dtpToDate.Value.ToString("dd-MMM-yyyy") & "'"
sql += " and invmast.f_type = 1 and im_qty > 0"
sql += "ORDER BY invmast.f_id"
Dim dt As New DataTable
Dim da = New SqlDataAdapter(sql, cnMain)
da.Fill(dt)
Dim rpt As New FutureTransaction
'Dim rptt As New FutureTransaction()
rpt.DataDefinition.FormulaFields("FundName").Text = "'" & FundName & "'"
rpt.DataDefinition.FormulaFields("FromDate").Text = "'" & dtpFromDate.Value.ToString("dd-MMM-yyyy") & "'"
rpt.DataDefinition.FormulaFields("ToDate").Text = "'" & dtpToDate.Value.ToString("dd-MMM-yyyy") & "'"
rpt.Refresh()
frmReportViewer.crvMain.ReportSource = rpt
frmReportViewer.crvMain.Refresh()
frmReportViewer.Show()
End Sub
So hope you guys will help me out.
Good afternoon, whatever your timezone is ..
My question is,
Is there a way to select all tables? just like how we select all columns?
Something like
Dim cmdsql As String = "SELECT * FROM *"
Situation:
I have 4 tables inside the database ("which I would not know the names if my client changes it") So I need a better way how to do those.
I wanna SELECT all the columns, FROM all the tables store it in a dataset, so I can iterate
if it matches the search criteria.
EDIT: This is my search code by the way.
SearchDataset.Clear()
lstSearchResults.Items.Clear()
btnSearch.Enabled = False
Dim cmdsql As String = "SELECT * FROM *" '- This variable holds the SQL command.
'-----------------------------------------
' Connect to the current connection string
'----------------------------------------
SYSTEM_MainClient.dbcon.Open()
'-----------------------------------------
' Setup the Where Clause
'----------------------------------------
If cboSearchBy.Text = "StudentID" Then
SearchAdapter = New OleDb.OleDbDataAdapter(cmdsql + " WHERE " + cboSearchBy.Text + " = " + txtSearchbox.Text, SYSTEM_MainClient.dbcon)
ElseIf cboSearchBy.Text = "Age" Then
SearchAdapter = New OleDb.OleDbDataAdapter(cmdsql + " WHERE " + cboSearchBy.Text + " = " + txtSearchbox.Text, SYSTEM_MainClient.dbcon)
Else
SearchAdapter = New OleDb.OleDbDataAdapter(cmdsql + " WHERE " + cboSearchBy.Text + " like '" + txtSearchbox.Text + "'", SYSTEM_MainClient.dbcon)
End If
SearchAdapter.Fill(SearchDataset, "SearchResults")
SYSTEM_MainClient.dbcon.Close()
If SearchDataset.Tables("SearchResults").Rows.Count > 0 Then
For i = 0 To SearchDataset.Tables("SearchResults").Rows.Count - 1
lstSearchResults.Items.Add(SearchDataset.Tables("SearchResults").Rows(i).Item("Last_Name").ToString + ", " + SearchDataset.Tables("SearchResults").Rows(i).Item("First_Name").ToString)
Next
Else
SYSTEM_MainClient.ShowInformation("No records matched with the search '" + txtSearchbox.Text + "'.", "Database Search")
txtSearchbox.Clear()
End If
btnSearch.Enabled = True
Basically what I want to happen, select all from all tables, and fill it in the dataset and iterate inside the dataset if there are matching result names based on the search criteria with my where clause.
Here this Is the code to select all the tables from the ms access database
SELECT MSysObjects.Name AS table_name FROM MSysObjects
WHERE (((Left([Name],1))<>"~") AND ((Left([Name],4))<>"MSys") AND ((MSysObjects.Type) In (1,4,6)))
order by MSysObjects.Name
Making some alteration to this query will help to select columns of table
I need to access data from a table. I have used the code like this:
string sql = "select * from bikesold "
+ "where model = '"+model+"'
+ "and mnth = '"+mnth+"' ";
The error is coming as follows:
ORA-00904: "MNTH": invalid identifier.
All the database connections are ok. I just need to confirm the Syntax for this code.
string sql = "select * from bikesold "
+ "where model = '"+model+"'"
+ "and mnth = '"+mnth+"' ";
you have missed the double quote in 2nd string.
For starters, your string is wrong. Try this instead:
string sql = "select * from bikesold "
+ "where model = '"+ model +
+ "' and mnth = '"+ mnt + "'";
Q: Does your table actually have a column named "mnth'?
I could use your advice on an approach for copying data between tables. I'm really trying to avoid RDBMS-specific SQL... The 2 tables are the same in all respects except name.
Concept:
My application uses data from a table (let's call it TableA). But this reference data changes almost daily, so I want to copy yesterday's off to make room for toady's data.
Right now, I use SMO to make an exact copy of TableA (schema), with unique (using date) names for the table, indices, keys, etc. No problemo. If there are any problems updating TableA with today's data, I can always restore yesterday's TableA (TableA_<yesterdayDate>). Both tables are on the same database.
I can't just use SMO's .rename, because it won't rename all the keys & indices...
So much for the premise.
Desired:
A non-SQL statement way to do so. I am heavily invested in EF6/Code First in this application, but as the name of the table changes each day, I can't just add tables/classes in DbContext 'just in case'.
I just feel so dirty using low level SQL...
SQL Server 2012
VB2012
EF6/Code First
P.S. I've tried a few times in the past to implement SQL statements (LINQ-ish) via the DbContext, and never got it to work-especially for SPs.
I can't find a cleaner way to do this. I tried to encapsulate all the logic into a single Function that returns a boolean on success/failure. Please orgive the roughness of the code!
NewTableName is just OldTableName_YYYMMDD. I could have used "SourceTableName", but this is just the first hack at it.
Public Function MoveAllRowsToNewTable(OldTableName As String, NewSchemaName As String, NewTableName As String, IndexColumnName As String) As Boolean
' OldTableName = "TableA", "TableB", ...
' NewSchemaName = "dbo"
' NewTableName = "TableA_20140325", etc.
' IndexColumnName = "ID" in my case, but whatever col is needed
'
Try
'===
'
' DROP target table (if exist)
'
If Me.DoesTableExist(NewSchemaName, NewTableName) Then
Dim CmdQ = Me.ctx.Database.ExecuteSqlCommand("DROP TABLE " & NewSchemaName & "." & NewTableName)
log.Debug("DROPPED TABLE " & NewTableName)
Else
NewTableName = NewSchemaName & "." & NewTableName
log.Debug("New table name: " & NewTableName)
End If
'
Dim numRows As Int32 = 0 ' holds # of rows in SourceTable to check if copy OK
Select Case OldTableName
Case "TableA"
Try
'===
'
' Count rows in source table
'
numRows = (Me.ctx.TableA).Count
'
'===
'
' Copy rows in source table, creating new table in the process
'
CmdQ = "SELECT * INTO " & NewTableName & " FROM " & OldTableName
Me.ctx.Database.ExecuteSqlCommand(CmdQ)
'
' create PK
'
Dim PKQ As String = "ALTER TABLE " & NewTableName & " ADD CONSTRAINT PK_" & NewTableName & "_ID PRIMARY KEY CLUSTERED (ID)"
CmdQ = ctx.Database.ExecuteSqlCommand(PKQ.ToString)
'
' create index
'
Dim NewTableIndexName As String = "idx_" & NewTableName.Replace(".", "_") ' indices can't have a '.' in them
Dim IdxQ As String = "CREATE INDEX " & NewTableIndexName & " ON " & NewTableName & " (" & IndexColumnName & ");"
CmdQ = ctx.Database.ExecuteSqlCommand(IdxQ.ToString)
'
' verify rows copied
'
Dim RowQ As Int32 = Me.ctx.Database.SqlQuery(Of Int32)("SELECT COUNT(*) AS rows FROM " & NewTableName).FirstOrDefault
log.Debug("TargetTableRows: " & RowQ.ToString)
If numRows = RowQ Then
log.Debug("MATCH!" & RowQ)
Else
log.Debug("NO MATCH! numRows: " & numRows & " RowQ: " & RowQ)
'
' rollback the move-the copy FAILED!
'
' XXX to-do
End If
Catch ex As Exception
[...]
End Try
'
Case "TableB"
[...]
I only have 3 source tables, so a Switch/Case is very practical in this early stage...
I'm still open to ideas, but I dug as far as I could, and I have to move on. Maybe I'll re-visit it something more elegant comes along!