Datatable Select all rows - sql

I want to insert into table for specific columns into table using select * from datatable.But it is giving me an array .. is there any way I can get the Insert work.
all I want to do is
Insert into table1 (id,name,status) select * from datatable
query += "Insert into " + tableName.ToLower() + "";
query += "(";
for (int i = 0; i < dt.Columns.Count; i++)
{
if (i != dt.Columns.Count - 1)
query += dt.Columns[i].ColumnName.ToLower() + ",";
else
query += dt.Columns[i].ColumnName.ToLower();
}
query += ")";
DataRow[] result = dt.Select();
query += "select * from " + result

You Can't use two sql Statements at once like that you have to separate them in two different objects or variables (It's sometimes allowed when you end each by a semicolon ; but not in your case )
try to get each cell value in the row
query += "Insert into " + tableName.ToLower() + "";
query += "(";
for (int i = 0; i < dt.Columns.Count; i++)
{
if (i != dt.Columns.Count - 1)
query += dt.Columns[i].ColumnName.ToLower() + ",";
else
query += dt.Columns[i].ColumnName.ToLower();
}
query += ")";
query += "values ( ";
string temQry=query;//you need it more than once
DataRow[] result = dt.Select();
for (int i = 0; i < dt.Rows.Count; i++){
for (int j = 0; j < dt.Columns.Count; j++){
if ((j+1)<dt.Columns.Count){
query += result[i].item(j) +"," ;
}
else {
query += result[i].item(j);}
}
query=temQry; //recover the query for each new row
}

Related

SQL: Automatic numbering

I've got a question about SQL language which I couldn't find an answer for. I want SQL to automatically insert a number based off how much rows there are. Using an ASP.NET website I'm adding new rows and deleting rows. This means when I delete rows I want the table to automatically respond to that.
It is pretty hard to explain for me, so I already did some thinking ofcourse. I can fill it in using a C# code but when a row is deleted it ofcourse does not automatically change.
if (kisten < 4)
{
staple = 1;
}
else
{
if (staple1 >= 4)
{
staple = stapel2 + 1;
}
else
{
stapel = stapel2;
}
}
So what this means is that one staple contains 4 blocks. But I want if one row gets removed from the staple the first row of the second staple gets added to the first staple, so it gets value '1'.
Hope I am clear enough. If not, please don't hesitate to ask.
EDIT:
I am using SQL Server indeed. Here is a clear example of what I mean:
This is when everything is inserted using C# and as u can see it works fine.
This is when rows get deleted. As you can see the column 'Stapel' does not automatically change the number
What I want when rows get deleted
So after hours of trying I found a solution which works perfectly. Like so:
SqlCommand cmd11 = new SqlCommand("select count(kistid) from [dbo].[kist] where rij = '" + rij + "'", con);
int countrij = (Int32)cmd11.ExecuteScalar();
int procent = (4 / countrij * 100);
int hoeveel;
int hoeveel2 = (countrij % 4);
int hoeveel1;
if (hoeveel2 == 0)
{
hoeveel = (countrij / 4);
hoeveel1 = hoeveel;
for (int i = 0; i < hoeveel; i++)
{
SqlCommand sqlquery5 = new SqlCommand("UPDATE TOP (" + countrij + ") Kist SET Stapel ='" + hoeveel1 + "' WHERE Rij ='" + rij + "'");
sqlquery5.CommandType = System.Data.CommandType.Text;
sqlquery5.Connection = con;
sqlquery5.ExecuteNonQuery();
hoeveel1 = hoeveel1 - 1;
countrij = countrij - 4;
}
}
else
{
hoeveel = ((countrij - hoeveel2) / 4) + 1;
hoeveel1 = hoeveel;
for (int i = 0; i < hoeveel; i++)
{
SqlCommand sqlquery5 = new SqlCommand("UPDATE TOP (" + countrij + ") Kist SET Stapel ='" + hoeveel1 + "' WHERE Rij ='" + rij + "'");
sqlquery5.CommandType = System.Data.CommandType.Text;
sqlquery5.Connection = con;
sqlquery5.ExecuteNonQuery();
hoeveel1 = hoeveel1 - 1;
countrij = countrij - hoeveel2;
hoeveel2 = 4;
}
}
To automatically do something in a database when UPDATE, DELETE or INSERT command is executed for a given table you have to use CREATE TRIGGER to define a new trigger.
For more information just read about usage of triggers in your specific database server. For example for SQL Server you can read this.

Fingerprint Hardware ID GetHexString

I found a fingerprint class in C# here
I'm trying to convert the function below to VB .NET but I am having issues with the line that reads s+ = (char)....Any help would be appreciated.
private static string GetHexString(byte[] bt)
{
string s = string.Empty;
for (int i = 0; i < bt.Length; i++)
{
byte b = bt[i];
int n, n1, n2;
n = (int)b;
n1 = n & 15;
n2 = (n >> 4) & 15;
if (n2 > 9)
s += ((char)(n2 - 10 + (int)'A')).ToString();
else
s += n2.ToString();
if (n1 > 9)
s += ((char)(n1 - 10 + (int)'A')).ToString();
else
s += n1.ToString();
if ((i + 1) != bt.Length && (i + 1) % 2 == 0) s += "-";
}
return s;
}
Is there a better way to write this function in VB.NET?
This
s += ((char)(n1 - 10 + (int)'A')).ToString();
is the same as
s &= Chr((n1 - 10 + Asc("A")))

how to get only first row of datatable with modified specific row value

I have query to just summary of total no of jobs running. now I just want some specific result if there is unique rows found like unique category id with assign job then ok with multiple record set. but no category found if is null then just only pass first record from datatable with modified text with 'ALL' as category name. can we achieve this result.
here is my query and some operations I'm doing with them.
string str = "";
DataTable dt = new DataTable();
str = "SELECT j.[JobID], p.[Id] As PreparedEmailID,p.[Title] AS 'PreparedEmailName',j.[CreatedOn],j.[CompletedOn],j.CategoryID,j.[SubscriberCount],j.[EmailsSent],c.[CategoryName] As SubscriberCategory,(SELECT TOP 1 [Message] FROM [LoggedMessages] WHERE [JobID] =j.[JobID] ORDER BY [LoggedMessageID] DESC) AS 'LoggedMessage',(SELECT [Name] FROM tbl_User_master u WHERE u.Id =j.UserID) As CreatedBy FROM [Jobs] AS j INNER JOIN [tbl_Email_master] AS p ON p.[Id] = j.[PreparedEmailID] INNER JOIN [tbl_User_master] AS u ON u.[Id]=j.[UserID] INNER JOIN tbl_Categories c ON c.Id = j.CategoryID OR (c.Id IS NOT NULL AND j.CategoryID IS NULL) where 1=1 ";
if (chk_date.Checked == true)
{
str += " and ( [CreatedOn] between '" + CommonLogic.Get_Date_From_String(txt_date_from.Text, 1);
str += "' and '" + CommonLogic.Get_Date_From_String(txt_date_to.Text, 2) + "' )";
}
if (string.IsNullOrEmpty(txttitle.Text.Trim()))
{
str += string.Empty;
}
else
{
str += " and p.Title like '%" + txttitle.Text.Trim() + "%'";
}
if (ddl_fromuser.SelectedItem.Text.ToString() == ".All")
{
str += string.Empty;
}
else
{
str += " and j.FromuserID = CONVERT(INT," + Convert.ToInt32(ddl_fromuser.SelectedValue.ToString()) + ")";
}
if (ddl_subcategories.SelectedItem.Text.ToString() == ".All")
{
str += string.Empty;
}
else
{
str += " and j.CategoryID = CONVERT(INT," + Convert.ToInt32(ddl_subcategories.SelectedValue.ToString()) + ")";
}
dt = obj.Get_Data_Table_From_Str(str);
if (dt.Rows.Count > 1)
{
dt.Rows[0]["SubscriberCategory"] = "ALL";
var topRows = dt.AsEnumerable().FirstOrDefault();
egrd.DataSource = topRows;
egrd.DataBind();
}
else
{
egrd.DataSource = dt;
egrd.DataBind();
}
ViewState["data"] = dt;
how ever this gives me error like no JobID found to this record set. whether it is still exists in record set.
please help me...
well I tried this solution but no success...……..
if (dt.Rows.Count > 1)
{
dt.Rows[0]["SubscriberCategory"] = "ALL";
var topRows = dt.AsEnumerable().GroupBy(j => j.Field<int>("JobID")).Select(j => j.First()).ToList();
egrd.DataSource = topRows;
egrd.DataBind();
}
it's gives me exception like DataBinding: 'System.Data.DataRow' does not contain a property with the name 'JobID'.
Just replace .ToList() with .CopyToDataTable() resolve my problem

How to run SQL query concurrently in one by one

I am developing one page like Daily SMS Log for retrieving info regarding SMS run in background. I have this SQL code:
First Section
--SELECT ROW_NUMBER() OVER (ORDER BY RowId DESC)AS RowNumber,p.CampaignName,
-- p.MobileNo,
-- p.Message,
-- p.CharCount,
-- p.strSenderID as Sender,
-- u.strUserName as UserId,
-- ds.strDR as DeliveryStatus,
-- ds.strDiscription as Original_DRStatus,
-- m.strMessageType as MessageType,
-- CONVERT(varchar(20) , p.ReceiveTime) as ReceiveTime,
-- CONVERT(varchar(20) , p.SendTime) as SendTime,
-- CONVERT(varchar(20) , p.DoneTime) as DoneTime,
-- p.RootId as Root,
-- sp.ProviderName,
-- (CASE intAccountType WHEN 1 THEN 'Promotional' WHEN 2 THEN 'Transactional' WHEN 3 THEN 'OptIn' END) as AccountType
-- INTO #Results3
-- FROM NEWSMSLOG_2019_01..LOG_010119 p
-- INNER JOIN deliverstatus ds ON p.DeliveryStatus = ds.intDR_status inner join users u on u.id = p.userid
-- left join senderids b on b.id = p.senderid
-- left join messagetype m on m.intcode = p.messagetype
-- left join smppproviders sp on sp.RootId=p.RootId
-- where 1=1
Second Section
-- SELECT *
-- FROM #Results3
-- SELECT
-- CampaignName,MobileNo,Message,CharCount,Sender,UserId,DeliveryStatus,
-- Original_DRStatus,MessageType,ReceiveTime,SendTime,DoneTime,Root,ProviderName,AccountType
-- FROM #Results3
-- WHERE RowNumber BETWEEN('1' -1) * '109299' + 1 AND((('1' -1) * '109299' + 1) + '109299') - 1
Here when I uncomment the first line to where 1=1 then rows retrieved with success. And after that commenting up those line I uncomment second section then result shows bunch of rows. Now it's works fine in Management Studio.
Now I just want this result to grid view and here is my code:
protected void Get_Data()
{
try
{
string str = "";
DataTable dt = new DataTable();
str = "SELECT ROW_NUMBER() OVER (ORDER BY RowId DESC)AS RowNumber,p.CampaignName,";
str += "p.MobileNo,";
str += "p.Message,";
str += "p.CharCount,";
str += "p.strSenderID as Sender,";
str += "u.strUserName as UserId,";
str += "ds.strDR as DeliveryStatus,";
str += "ds.strDiscription as Original_DRStatus,";
str += "m.strMessageType as MessageType,";
str += "CONVERT(varchar(20), p.ReceiveTime) as ReceiveTime,";
str += "CONVERT(varchar(20), p.SendTime) as SendTime,";
str += "CONVERT(varchar(20), p.DoneTime) as DoneTime,";
str += "p.RootId as Root,";
str += "sp.ProviderName,";
str += "(CASE intAccountType WHEN 1 THEN 'Promotional' WHEN 2 THEN 'Transactional' WHEN 3 THEN 'OptIn' END) as AccountType";
str += " INTO #Results3 ";
str += " FROM NEWSMSLOG_2019_01..LOG_010119 p ";
str += " INNER JOIN deliverstatus ds ON p.DeliveryStatus = ds.intDR_status inner join users u on u.id = p.userid";
str += " left join senderids b on b.id = p.senderid";
str += " left join messagetype m on m.intcode = p.messagetype";
str += " left join smppproviders sp on sp.RootId = p.RootId";
str += " where 1 = 1 ";
if(ddl_users.SelectedItem.Text.ToString() == "All")
{
str += string.Empty;
}
else
{
str += " and p.userid = ' + CONVERT(varchar(5),"+ Convert.ToInt32(ddl_users.SelectedValue.ToString())+") + '";
}
if (ddl_sender.SelectedItem.Text.ToString() == "All")
{
str += string.Empty;
}
else
{
str += " and p.Senderid = '+CONVERT(varchar(10),"+Convert.ToInt32(ddl_sender.SelectedValue.ToString())+")+'";
}
if(!string.IsNullOrEmpty(txt_mobileno.Text.Trim()))
{
str += " and p.MobileNo like '' % '"+txt_mobileno.Text.Trim()+"' % ''";
}
else
{
str += string.Empty;
}
if(ddl_delevery.SelectedItem.Text.ToString() =="All")
{
str += string.Empty;
}
else
{
str += " and p.Deliverystatus in ('+CONVERT(varchar(10),"+Convert.ToInt32(ddl_sender.SelectedValue.ToString())+")+')'";
}
if(!string.IsNullOrEmpty(txt_CompaignName.Text.Trim()))
{
str += " and p.CampaignName like ''%'"+txt_CompaignName.Text.Trim()+"'%'' '";
}
else
{
str += string.Empty;
}
if(ddl_account.SelectedItem.Text.ToString() == "All")
{
str += string.Empty;
}
else
{
str += " and p.accounttype = '+CONVERT(varchar(2),"+Convert.ToInt32(ddl_account.SelectedValue.ToString())+")+'";
}
obj.Execute_Query(str);
string str1 = " SELECT * FROM #Results3";
str1 += " SELECT";
str1 += " CampaignName,MobileNo,Message,CharCount,Sender,UserId,DeliveryStatus,";
str1 += "Original_DRStatus,MessageType,ReceiveTime,SendTime,DoneTime,Root,ProviderName,AccountType";
str1 += " FROM #Results3";
str1 += " WHERE RowNumber BETWEEN('1' - 1) * '500' + 1 AND((('1' - 1) * '500' + 1) + '500') - 1";
str1 += " DROP TABLE #Results3";
dt = obj.Get_Data_Table_From_Str(str1);
ViewState["data"] = dt;
egrd.DataSource = dt;
egrd.DataBind();
ViewState["data"] = dt;
}
catch (Exception ex)
{
CommonLogic.SendMailOnError(ex);
}
}
But I have no records found in grid view. What's problem is that?
--------------------------Updated--------------------------------------------
namespace BulkSMSSystem.App_Code.DAL
{
public class DAL_General : DataAccess
{
public DataTable Get_Data_Table_From_Str(string str, string cnn_type = "NEWBULKSMS")
{
DataTable dt = new DataTable();
GetConnection(cnn_type);
dt = GetDataTableByQuery(str);
return dt;
}
public void Execute_Query(string str, string cnn_type = "NEWBULKSMS")
{
GetConnection(cnn_type);
GetExecuteNonQueryByStr(str);
}
public object Execute_Scalar(string str, string cnn_type = "NEWBULKSMS")
{
GetConnection(cnn_type);
object rtn = GetScalarOfStr(str);
return rtn;
}
---------------------------Updated 2-------------------------------------
public DataTable GetDataTableByQuery(string str_query)
{
try
{
mobj_SqlCommand.CommandText = str_query;
mobj_SqlCommand.CommandTimeout = mint_CommandTimeout;
mobj_SqlCommand.CommandType = CommandType.Text;
//mobj_SqlConnection.Open();
SqlDataAdapter adpt = new SqlDataAdapter(mobj_SqlCommand);
DataTable ds = new DataTable();
adpt.Fill(ds);
return ds;
}
catch (Exception ex)
{
throw ex;
}
finally
{
CloseConnection();
}
}
public void GetExecuteNonQueryByStr(string query_str)
{
try
{
mobj_SqlCommand.CommandType = CommandType.Text;
mobj_SqlCommand.CommandText = query_str;
mobj_SqlCommand.Connection = mobj_SqlConnection;
mobj_SqlCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
CloseConnection();
}
}
--------------------------Updated 3-----------------------------------
protected void GetConnection(string cnn_db = "NEWBULKSMS")
{
try
{
string Cnn_Str = "";
string ServerName = "SHREE-PC";
string DBUserName = string.Empty;
string DBPassword = string.Empty;
DBPassword += "c#" + Convert.ToChar(49);
string Database = cnn_db;
Cnn_Str = "Data Source=" + ServerName + "; UID=" + DBUserName + "; PWD=" + DBPassword + "; Database=" + Database+";Integrated Security = True";
//Cnn_Str = "Data Source=SHREE-PC;Initial Catalog=Project_DB_MNG;Integrated Security=True";
mstr_ConnectionString = Cnn_Str;
mobj_SqlConnection = new SqlConnection(mstr_ConnectionString);
mobj_SqlCommand = new SqlCommand();
mobj_SqlCommand.CommandTimeout = mint_CommandTimeout;
mobj_SqlCommand.CommandType = CommandType.StoredProcedure;
mobj_SqlCommand.Connection = mobj_SqlConnection;
mobj_SqlConnection.Open();
}
catch (Exception ex)
{
throw new Exception("Error initializing data class." + Environment.NewLine + ex.Message);
}
}
--------------------------Upadted 4--------------------------------------
As you are using temp table with one # sign it means that a temporary table will exists only during your session. However, if you create a temporary table with ##, then every user will be able to use that one, and none other can create a temp table with the same name, but it will be deleted when the owner session expired or disconnect.
So try to use in your code:
...
str += " INTO ##Results3 ";
...
And:
string str1 = " SELECT * FROM ##Results3";
str1 += " SELECT";
str1 += " CampaignName,MobileNo,Message,CharCount,Sender,UserId,DeliveryStatus,";
str1 += "Original_DRStatus,MessageType,ReceiveTime,SendTime,DoneTime,Root,ProviderName
,AccountType";
str1 += " FROM ##Results3";
str1 += " WHERE RowNumber BETWEEN('1' - 1) * '500' + 1 AND((('1' - 1) * '500'
+ 1) + '500') - 1";
str1 += " DROP TABLE ##Results3";

Clear Previous selection of Dropdown in EXCEL usingApache POI

I have developed the excel using the Apache NPOI dll using HSSFWORKBOOK. But in my excel having 3 dependent dropdowns one in each other.
Here my question is I am unable to clear the cell value of dependent dropdowns. Let say like dropdown1 have country values and on the selection of this dropdown2 state values got a filter and selected one of the state. Now if I changed the country again able to filter the data but whatever the previous state selection not getting cleared.
code ref:
No, i am just referring the list of columns data from sheet2 to sheet1 using the formulae. below is code ref:
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
//if (i >= MaxRowCount)
//{
// sheet2.CreateRow(1000 + i).CreateCell(1).SetCellValue(ds.Tables[0].Rows[i][1].ToString());
// MaxRowCount += 1;
//}
//else
// sheet2.GetRow(1000 + i).CreateCell(1).SetCellValue(ds.Tables[0].Rows[i][1].ToString());
if (CategoryCount == 250)
{
rownumber = rownumber + 3000;
CategoryCount = 16;
MaxRowCount = 0;
}
DataRow[] DR = ds.Tables[1].Select("LOCATION_ID=" + ds.Tables[0].Rows[i][0].ToString());
int RowCount = 0;
//int rownumber = 1000;
foreach (DataRow d in DR)
{
if (RowCount >= MaxRowCount)
{
sheet2.CreateRow(rownumber + RowCount).CreateCell(CategoryCount).SetCellValue(d[0].ToString());
MaxRowCount += 1;
}
else
{
sheet2.GetRow(rownumber + RowCount).CreateCell(CategoryCount).SetCellValue(d[0].ToString());
}
RowCount++;
}
IName DeptHierarchy_Dept = hssfworkbook.CreateName();
DeptHierarchy_Dept.NameName = "XDeptHierarchy_Dept_SUB" + (XDeptHierarchy_Dept_SUBCount).ToString();
if (CategoryCount / 26 < 1)
DeptHierarchy_Dept.RefersToFormula = "'Template Field Specs2'!$" + ((char)(65 + CategoryCount)).ToString() + "$" + (StartRowNumber + 1) + ":$" + ((char)(65 + CategoryCount)).ToString() + "$" + ((StartRowNumber + 1) + (RowCount == 0 ? 0 : RowCount - 1)).ToString();
else
DeptHierarchy_Dept.RefersToFormula = "'Template Field Specs2'!$" + ((char)(65 + (CategoryCount / 26) - 1)).ToString() + ((char)(65 + CategoryCount % 26)).ToString() + "$" + (StartRowNumber + 1) + ":$" + ((char)(65 + (CategoryCount / 26) - 1)).ToString() + ((char)(65 + CategoryCount % 26)).ToString() + "$" + ((StartRowNumber + 1) + (RowCount == 0 ? 0 : RowCount - 1)).ToString();
CategoryCount++;
XDeptHierarchy_Dept_SUBCount++;
You are looking for "Dependent Drop Down Lists". You'll have to be creative for your formula because your row will keep changing.
one approach i can think of is store the list of "Country-capital" on named region some where deep in excel. On selection of country, parse and find the capital from named region and populate your target cell.
Please see the documentation.
Also this link;