I have some code which collect all users from Active Directory and INSERTs them into my database. After I have inserted all users which don't already exist in my database I want to count how many new users I added to the database.
So far want I create is this which is function to Execute store procedure
public void ExcStrPrc(string Username, string DisplayName, bool isEnable, bool PassNevExp)
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True");
SqlCommand cmd = new SqlCommand("ADProcTemp", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Username", Username.ToString().Trim());
cmd.Parameters.AddWithValue("#DisplayName", DisplayName.ToString().Trim());
cmd.Parameters.AddWithValue("#isEnabled", Convert.ToInt32(isEnable));
cmd.Parameters.AddWithValue("#PassNevExp", Convert.ToInt32(PassNevExp));
conn.Open();
int k = cmd.ExecuteNonQuery();
if (k != 0)
{
Console.WriteLine("Record Inserted Succesfully into the Database");
}
conn.Close();
}
And here is my main program
public static List<Korisnik> VratiKorisnike()
{
List<Korisnik> lstADUsers = new List<Korisnik>();
string sDomainName = "saostest";
string DomainPath = "LDAP://" + sDomainName;
string fileLoc = #"C:\output.txt";
DirectoryEntry searchRoot = new DirectoryEntry(DomainPath);
DirectorySearcher search = new DirectorySearcher(searchRoot);
search.Filter = "(&(objectClass=user)(objectCategory=person))";
search.PropertiesToLoad.Add("samaccountname"); // Username
search.PropertiesToLoad.Add("displayname"); // display name
search.PropertiesToLoad.Add("userAccountControl"); // isEnabled
search.PropertiesToLoad.Add("pwdLastSet"); //passwordExpires
DataTable resultsTable = new DataTable();
resultsTable.Columns.Add("samaccountname");
resultsTable.Columns.Add("displayname");
resultsTable.Columns.Add("Neaktivan");
resultsTable.Columns.Add("dontexpirepassword");
SearchResult result;
SearchResultCollection resultCol = search.FindAll();
if (resultCol != null)
{
for (int counter = 0; counter < resultCol.Count; counter++)
{
string UserNameEmailString = string.Empty;
result = resultCol[counter];
if (result.Properties.Contains("samaccountname")
&& result.Properties.Contains("displayname"))
{
int userAccountControl = Convert.ToInt32(result.Properties["userAccountControl"][0]);
string samAccountName = Convert.ToString(result.Properties["samAccountName"][0]);
int isEnable;
int Dont_Expire_Password;
if ((userAccountControl & 2) > 0)
{
isEnable = 0;
}
else
{
isEnable = 1;
}
if ((userAccountControl & 65536) > 0)
{
Dont_Expire_Password = 1;
}
else
{
Dont_Expire_Password = 0;
}
Korisnik korisnik = new Korisnik();
korisnik.Username = (result.Properties["samaccountname"][0]).ToString();
korisnik.DisplayName = result.Properties["displayname"][0].ToString();
korisnik.isEnabled = Convert.ToBoolean(result.Properties["userAccountControl"][0]);
DataRow dr = resultsTable.NewRow();
dr["samaccountname"] = korisnik.Username.ToString();
dr["displayname"] = korisnik.DisplayName.ToString();
dr["neaktivan"] = Math.Abs(isEnable);
dr["dontexpirepassword"] = Dont_Expire_Password;
resultsTable.Rows.Add(dr);
// Poziva se store procedura
Program p = new Program();
p.ExcStrPrc(korisnik.Username.ToString().Trim(), korisnik.DisplayName.ToString().Trim(), Convert.ToBoolean(isEnable), Convert.ToBoolean(Dont_Expire_Password));
//Ukupan broj dodanih novih usera
string connectionString = #"Data Source = (LocalDb)\MSSQLLocalDB; Initial Catalog = DesignSaoOsig1; Integrated Security = True";
System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(connectionString);
sqlConnection.Open();
System.Data.SqlClient.SqlCommand sqlCommand = new System.Data.SqlClient.SqlCommand("SELECT COUNT(*) FROM [dbo].[tblZaposleni_AD]");
sqlCommand.Connection = sqlConnection;
int RecordCount = Convert.ToInt32(sqlCommand.ExecuteScalar());
Console.WriteLine("Ukupan broj dodanih novi usera:", sqlCommand);
lstADUsers.Add(korisnik);
}
}
var json = JsonConvert.SerializeObject(resultCol, Formatting.Indented);
var res = json;
Console.WriteLine("Ispis uspjesno obavljen");
Console.ReadLine();
File.WriteAllText(fileLoc, json);
}
return lstADUsers;
}
}
}
Right here I add these logic
string connectionString = #"Data Source = (LocalDb)\MSSQLLocalDB; Initial Catalog = DesignSaoOsig1; Integrated Security = True";
System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(connectionString);
sqlConnection.Open();
System.Data.SqlClient.SqlCommand sqlCommand = new System.Data.SqlClient.SqlCommand("SELECT COUNT(*) FROM [dbo].[tblZaposleni_AD]");
sqlCommand.Connection = sqlConnection;
int RecordCount = Convert.ToInt32(sqlCommand.ExecuteScalar());
Console.WriteLine("Ukupan broj dodanih novi usera:", sqlCommand);
But here is problem which I didn't get any result (number)? Anyone how can help me to solve this problem?
Stored Procedure
CREATE PROCEDURE ADProcTemp
#Username varchar(250),
#DisplayName varchar(70),
#isEnabled tinyint,
#PassNevExp tinyint
AS
set nocount on
BEGIN
IF NOT EXISTS (SELECT TOP 1 PrezimeIme FROM [dbo].[tblZaposleni_AD] with (NOLOCK) WHERE NetworkLogin = #Username)
BEGIN
IF(#isEnabled = 1)
INSERT INTO [dbo].[tblZaposleni_AD](NetworkLogin,PrezimeIme,Status,PassNevExp)
VALUES (#Username, #DisplayName, #isEnabled,#PassNevExp)
END
ELSE
BEGIN
UPDATE [dbo].[tblZaposleni_AD]
SET Status = #isEnabled
WHERE NetworkLogin = #Username AND Status <> #isEnabled
END
END
First in your stored procedure you need to remove SET NOCOUNT ON in order to allow the sp to return the number of row affected.
Then in your c# code instead of
int RecordCount = Convert.ToInt32(sqlCommand.ExecuteScalar());
You need to call this
int RecordCount = Convert.ToInt32(sqlCommand.ExecuteNonQuery());
From the MSDN doc :
ExecuteScalar
Returns
Object
The first column of the first row in the result set, or a null reference (Nothing in Visual Basic) if the result set is empty. Returns a maximum of 2033 characters.
ExecuteNonQuery
Returns
Int32
The number of rows affected.
Related
public int UpdateAmount(List<MyTable> myBizObjList)
{
SqlTransaction sqltxn;
DbClass db = new DbClass();
SqlConnection cs;
cs = db.GetConnection();
string commandText = #"Update MyTable Set amt = #amt where empno = #empno and mydate = #mydate";
int x = myBizObjList.Count;
int y = 0,rowsaffected;
cs.Open();
using (cs)
{
sqltxn = cs.BeginTransaction();
foreach (MyTable myBizObj in myBizObjList)
{
SqlCommand command = new SqlCommand(commandText, cs, sqltxn);
command.Parameters.Add("#empno", SqlDbType.Int);
command.Parameters["#empno"].Value = myBizObj.Empno;
command.Parameters.Add("#mydate", SqlDbType.Date);
command.Parameters["#mydate"].Value = myBizObj.Mydate;
command.Parameters.Add("#amt", SqlDbType.Decimal);
command.Parameters["#amt"].Value = myBizObj.Amt;
try
{
rowsAffected = command.ExecuteNonQuery();
if (rowsAffected == 1)
y++;
}
catch (Exception ex)
{
throw (ex);
}
}
if (y == x)
{
sqltxn.Commit();
}
else
{
sqltxn.Rollback();
y = 0;
}
cs.Close();
return y;
}
}
Question: I am querying a table and getting say 50K records which I am converting to a List of objects. I am processing the List in my BLL and sending to my DAL. The above is a method in my DAL. Is there a better way? I am also checking if all rows are updated & then Commit or Rollback.
You can convert this to a table-valued parameter.
First we need a table type:
CREATE TYPE dbo.MyTVP (
empno int not null,
mydate date not null,
amt decimal not null
primary key (empno, mydate)
);
Then we pass it through. You don't necessarily need a stored procedure, you can do this as an ad-hoc batch:
public int UpdateAmount(List<MyTable> myBizObjList)
{
var table = new DataTable();
table.Columns.Add("empno", typeof(int));
table.Columns.Add("mydate", typeof(datetime));
table.Columns.Add("amt", typeof(decimal));
foreach (MyTable myBizObj in myBizObjList)
table.Rows.Add(myBizObj.Empno, myBizObj.Mydate, myBizObj.Amt);
const string commandText = #"
Update tbl
Set amt = t.amt
FROM MyTable AS tbl
JOIN #tmp AS t ON t.empno = tbl.empno AND t.mydate = tbl.mydate;
";
using (var cs = db.GetConnection())
{
SqlCommand command = new SqlCommand(commandText, cs, sqltxn);
command.Parameters.Add(
new SqlParameter("#tmp", SqlDbType.Structured)
{
Direction = ParameterDirection.Input,
TypeName = "dbo.MyTVP",
Value = table
});
cs.Open();
return command.ExecuteNonQuery();
}
}
I get this error when saving 2 or more values from the gridview:
The connection was not closed. The connection's current state is open
But the process goes through and it saves and updates the data. How can I remove this error?
Here is my code:
for(int i = 0; i < gvModal.Rows.Count; i++)
{
string dateA = DateTime.Now.ToString("yyyy-MM-dd");
Utility u = new Utility();
string conn = u.connect();
Label type = (Label)gvModal.Rows[i].Cells[1].FindControl("lbltype");
Label model = (Label)gvModal.Rows[i].Cells[2].FindControl("lblModel");
Label quantity = (Label)gvModal.Rows[i].Cells[3].FindControl("lblQuan");
Label unit = (Label)gvModal.Rows[i].Cells[4].FindControl("lblUnit");
int bal = Convert.ToInt32(gvModal.Rows[i].Cells[4].Text);
int forIssue = 0;
int forPO = 0;
if (bal != 0)
{
forIssue = 1;
forPO = 0;
}
else
{
forIssue = 0;
forPO = 1;
}
SqlConnection connUser = new SqlConnection(conn);
SqlCommand read = connUser.CreateCommand();
string query = "INSERT INTO Mosef_Alert values (#Mosef_No, #Branch, #BU, #Dept, #Section, #Requisitioner, #Accepted, #Date_Accepted, #Reason, #MOSEF_Date, #type, #model, #quantity, #unit)";
connUser.Open();
read.CommandText = query;
read.Parameters.Add(new SqlParameter("#Mosef_No", transIDs));
read.Parameters.Add(new SqlParameter("#Branch", branch));
read.Parameters.Add(new SqlParameter("#BU", bu));
read.Parameters.Add(new SqlParameter("#Dept", dept));
read.Parameters.Add(new SqlParameter("#Section", sec));
read.Parameters.Add(new SqlParameter("#Requisitioner", requisitioner));
read.Parameters.Add(new SqlParameter("#Accepted", accept));
read.Parameters.Add(new SqlParameter("#Date_Accepted", dateA));
read.Parameters.Add(new SqlParameter("#Reason", reason));
read.Parameters.Add(new SqlParameter("#MOSEF_Date", lblDateFiled.Text));
read.Parameters.Add(new SqlParameter("#type", type.Text));
read.Parameters.Add(new SqlParameter("#model", model.Text));
read.Parameters.Add(new SqlParameter("#quantity", quantity.Text));
read.Parameters.Add(new SqlParameter("#unit", unit.Text));
read.Parameters.Add(new SqlParameter("#For_PO", forPO));
read.Parameters.Add(new SqlParameter("#For_Issuance", forIssue));
read.ExecuteNonQuery();
read.Parameters.Clear();
}
ExecuteUpdate(accept);
UpdateStatus();
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(#"<script type ='text/javascript'>");
sb.Append("alert('Records Updated');");
sb.Append("$('#editModal').modal('hide');");
sb.Append(#"</script>");
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "EditHideModalScript", sb.ToString(), false);
}
public void UpdateStatus()
{
Utility u = new Utility();
string conn = u.connect();
SqlConnection connUser = new SqlConnection(conn);
SqlCommand read = connUser.CreateCommand();
for(int i = 0; i < gvModal.Rows.Count; i++)
{
Label ItemID = (Label)gvModal.Rows[i].Cells[1].FindControl("lblID");
Label stat = (Label)gvModal.Rows[i].Cells[8].FindControl("ItemStatus");
int balance = Convert.ToInt32(gvModal.Rows[i].Cells[4].Text);
string status;
if(balance != 0)
{
status = "For Issuance";
}
else
{
status = "For PO";
}
string upd = "UPDATE ItemTransaction SET ItemStatus = '" + status +"' WHERE ID = '"+ ItemID.Text +"'";
connUser.Open();
read.CommandText = upd;
read.Parameters.Clear();
read.ExecuteNonQuery();
}
}
public void ExecuteUpdate(int stat)
{
string upStat = null;
if (stat == 1)
{
upStat = "Accepted";
}
else
{
upStat = "Denied";
}
string id = transID.Text;
Utility u = new Utility();
string conn = u.connect();
SqlConnection connUser = new SqlConnection(conn);
string up = "UPDATE MosefTransaction SET TransStatus = '"+ upStat +"' WHERE TransactionID = '"+ id +"'";
connUser.Open();
SqlCommand cm = new SqlCommand(up, connUser);
//cm.Parameters.AddWithValue("#ID", id);
//cm.Parameters.AddWithValue("#TransStatus", upStat);
cm.Parameters.Clear();
cm.ExecuteNonQuery();
connUser.Close();
}
First thing you have to notice that, your plain text query opens a wide door for SqlInjection. So use parameterized queries. Now let me come to your code,
The problem is with the UpdateStatus method, In which you opened the connection while iteration and leave it without closing, so when you are trying to open the connection again in next iteration it throws the error. You can avoid this in many ways:
Close the connection in each iteration using connUser.Close()
You can use ConnectionState Enumeration to Check The connection state before opening a new connection. and open it only when the status is not open.
This can be done by using the following code:
if (connUser.State != ConnectionState.Open)
connUser.Open();
3. Open the Connection outside the Loop and use the same through-out the loop. Clear the parameters in each iteration after executing the query.
For example consider the code:
using (SqlConnection connUser = new SqlConnection(conn))
{
string upd = "UPDATE ItemTransaction SET ItemStatus = #status WHERE ID = #id";
connUser.Open();
SqlCommand commandSQL = connUser.CreateCommand();
for (int i = 0; i < gvModal.Rows.Count; i++)
{
// Get values here using your code
commandSQL.Parameters.Add("#status", SqlDbType.VarChar).Value = status;
commandSQL.Parameters.Add("#id", SqlDbType.VarChar).Value = ItemID.Text;
commandSQL.ExecuteNonQuery();
commandSQL.Parameters.Clear();
}
}
Note: The best option is the third one, I prefer you to follow that, The remaining notes to your knowledge, which will help you in other situations;
[WebMethod]
public List<reports> getMyReports( int user_id )
{
string cs = ConfigurationManager.ConnectionStrings["ReportDB"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("getAllReportsByUserID", con);
cmd.CommandType = CommandType.StoredProcedure;
List<reports> repers = new List<reports>();
//users[][] liser = new users[][];
SqlParameter user_id_parameter = new SqlParameter("#user_id", user_id);
cmd.Parameters.Add(user_id_parameter);
reports report = new reports();
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
report.id = Convert.ToInt32(reader["id"]);
report.title = reader["title"].ToString();
report.description = reader["description"].ToString();
report.anonymous = (bool)reader["anonymous"];
report.location = reader["location"].ToString();
report.status = reader["status"].ToString();
report.category = reader["category"].ToString();
report.date = (DateTime)reader["date"];
report.picture_url = reader["picture_url"].ToString();
report.admin_id = Convert.ToInt32(reader["admin_id"]);
repers.Add(report);
}
return repers;
}
}
I have the top function that calls the following stored procedure:
CREATE Proc [dbo].[getAllReportsByUserID]
#user_id int
as
Begin
Select
id,
title,
description,
anonymous,
location,
status,
category,
date,
picture_url,
admin_id
from reports
where user_id = #user_id
End
I have tested the procedure individually and it works fine. Yet, when I test the WebService created above I get a list with the last value duplicated along the whole list.
Can someone please help me figure out why do I get the same (last)value repeated over and over again?
By creating the report object before the loop and reusing it repeatedly, you insert a reference to that same object multiple times in your list.
You should create the report object inside your loop:
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
reports report = new reports();
report.id = Convert.ToInt32(reader["id"]);
report.title = reader["title"].ToString();
report.description = reader["description"].ToString();
report.anonymous = (bool)reader["anonymous"];
report.location = reader["location"].ToString();
report.status = reader["status"].ToString();
report.category = reader["category"].ToString();
report.date = (DateTime)reader["date"];
report.picture_url = reader["picture_url"].ToString();
report.admin_id = Convert.ToInt32(reader["admin_id"]);
repers.Add(report);
}
return repers;
I need select the maximum ID of PolygonId column. I save my data like this
string sql = "create table Polygons (PolygonId int, PointId int, X double, Y double)";
// Выполнение нашей команды
using (SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection))
{
command.ExecuteNonQuery();
}
int pointId = 1;
for (int i = 0; i < listOfCustomPolygons.Count; i++)
for (int j = 0; j < listOfCustomPolygons[i].listOfVertexes.Count; j++)
{
string strSQL =
string.Format("INSERT INTO Polygons (PolygonId,PointId,X,Y) Values ('{0}','{1}','{2}','{3}')",
i+1,pointId,listOfCustomPolygons[i].listOfVertexes[j].X,
listOfCustomPolygons[i].listOfVertexes[j].Y );
pointId++;
using (SQLiteCommand insertCommand = new SQLiteCommand(strSQL, m_dbConnection))
{
insertCommand.ExecuteNonQuery();
}
}
After this I want select the max value from table Polygons and column PolygonId, but I got an IndexOutOfRangeException. How a can solve this problem?
using (SQLiteConnection connection = new SQLiteConnection("Data Source=" + openFileDialog.FileName + ";Version=3;"))
{
connection.Open();
string selectMaxId = "Select Max(PolygonId) From Polygons";
string selectQuery = "Select * From Polygons";
SQLiteCommand selectMaxCmd = new SQLiteCommand(selectMaxId,connection);
SQLiteDataReader dataReader = selectMaxCmd.ExecuteReader();
int maxId = Convert.ToInt32(dataReader["Select Max(PolygonId) From Polygons"]); // This is don't work! Why?
I found out the solution! It should look like
string selectMaxId = "Select Max(PolygonId) From Polygons";
SQLiteCommand selectMaxCmd = new SQLiteCommand(selectMaxId,connection);
object val = selectMaxCmd.ExecuteScalar();
int maxId = int.Parse(val.ToString());
I hope it can help somebody who face with similar problem)
First of all don't create table every time you run your code :) But you probably know that
You type like this:
int maxId = Convert.ToInt32(dataReader["Select Max(PolygonId) From Polygons"]);
Try this:
string selectMaxId = "Select Max(PolygonId) From Polygons";
SQLiteCommand selectMaxCmd = new SQLiteCommand(selectMaxId,connection);
SQLiteDataReader dataReader = selectMaxCmd.ExecuteReader();
int maxID = -1;
while(dataReader.read())
{
maxID = (int)dataReader.GetValue(0);
}
//This Works for me in WPF C#:
int MaxNum=0;
sqliteCon.Open();
string Query = "SELECT MAX(Promo_No)FROM Promo_File";
SQLiteCommand createCommand = new SQLiteCommand(Query, sqliteCon);
SQLiteDataReader DR = createCommand.ExecuteReader();
while (DR.Read())
{
MaxNum = DR.GetInt16(0);
}
sqliteCon.Close();
I had the same problem!
You have to learn the difference method of SQLiteCommand.
1.SQLiteCommand.ExecuteReader(). Get a SqlDataReader.
2.SQLiteCommand.ExecuteScalar(). Get a single value from the database.
Microsoft Doc:
cmd.CommandText = "SELECT COUNT(*) FROM dbo.region";
Int32 count = (Int32) cmd.ExecuteScalar();
How do I get the last id created in the policy table and store it into a variable so that I can use it for another table called backupspec table.
System.Data.SqlClient.SqlConnection dataConnection = new SqlConnection();
dataConnection.ConnectionString =
#"Data Source=JAGMIT-PC\SQLEXPRESS;Initial Catalog=SumooHAgentDB;Integrated Security=True";
System.Data.SqlClient.SqlCommand dataCommand = new SqlCommand();
dataCommand.Connection = dataConnection;
//tell the compiler and database that we're using parameters (thus the #first, #last, #nick)
dataCommand.CommandText = ("Insert Policies ( PolicyName, PolicyDesc, TimeAdded,OSFlag, CreateVSSSnapshot, CreateAuditLogForRecoveries, AllowUsersToOverwriteFiles, AutoHandleEnvErrors, NotifyOnEnvErrorCount, NotifyOnFileFailure, NotifyOnFileFailureCount, NotifyOnLackOfPCContact, NotifyOnLackOfPCContactDays, NotifyOnRecoveryFailures, NotifyOnRecoveryFailureReason) values (#pn,#pd,#TimeAdded,#os,#vss,#al,#uow,#hee,#oeec,#off,#offc,#oloc,#olocd,#orf,#orfr)");
dataCommand.Parameters.AddWithValue("#pn",pn);
dataCommand.Parameters.AddWithValue("#pd",pd);
dataCommand.Parameters.AddWithValue("#TimeAdded",TimeAdded);
dataCommand.Parameters.AddWithValue("#os",os);
dataCommand.Parameters.AddWithValue("#vss",vss);
dataCommand.Parameters.AddWithValue("#al",al);
dataCommand.Parameters.AddWithValue("#uow",uow);
dataCommand.Parameters.AddWithValue("#hee",hee);
dataCommand.Parameters.AddWithValue("#oeec",oeec);
dataCommand.Parameters.AddWithValue("#off",off);
dataCommand.Parameters.AddWithValue("#offc",offc);
dataCommand.Parameters.AddWithValue("#oloc",oloc);
dataCommand.Parameters.AddWithValue("#olocd",olocd);
dataCommand.Parameters.AddWithValue("#orf",orf);
dataCommand.Parameters.AddWithValue("#orfr",orfr);
dataConnection.Open();
dataCommand.ExecuteNonquery();
dataConnection.Close();
ArrayList jaja = (ArrayList)Session["BackupSpecList"];
for (int i = 0; i < jaja.Count; i++)
{
BackupSpecEntry bsp = (BackupSpecEntry)jaja[i];
string path = bsp.path;
string inclExcl = bsp.inclExcl;
byte inclExclFlags = bsp.inclExclFlags;
bool indexContents = bsp.indexContents;
int serverBackupSpecId = bsp.serverBackupSpecId;
int freq = bsp.freq;
int retention = bsp.retention;
int policyID =DONT KNOW HOW TO GET THIS VALUE;
long specChangeTime = 0;
long backupTime = 0;
dataCommand.CommandText = ("Insert BackupSpec (PolicyID, Path, ServerBackupSpecID, Freq, Retention, InclExclFlags, InclExcl, IndexContents, SpecChangeTime, BackupTime) values (#policyID,#path,#serverBackupSpecId,#freq,#retention,#inclExclFlags,#inclExcl,#indexContents,#specChangeTime,#backupTime)");
dataCommand.Parameters.AddWithValue("#policyID", policyID);
dataCommand.Parameters.AddWithValue("#path", path);
dataCommand.Parameters.AddWithValue("#serverBackupSpecId", serverBackupSpecId);
dataCommand.Parameters.AddWithValue("#freq", freq);
dataCommand.Parameters.AddWithValue("#retention", retention);
dataCommand.Parameters.AddWithValue("#inclExclFlags", inclExclFlags);
dataCommand.Parameters.AddWithValue("#inclExcl", inclExcl);
dataCommand.Parameters.AddWithValue("#indexContents", indexContents);
dataCommand.Parameters.AddWithValue("#specChangeTime", specChangeTime);
dataCommand.Parameters.AddWithValue("#backupTime", backupTime);
dataConnection.Open();
dataCommand.ExecuteNonQuery();
dataConnection.Close();
}
I am getting error with the label id...
can some 1 help me with this..??
I am not getting the last policyID created after inserting please help...
Please help
Use scope_identity:
strSQL = "INSERT INTO Policies (...) VALUES (#vals....);SELECT #result = scope_identity()"
SQLCommand.CommandText = strSQL;
SQLCommand.Parameters.Add("#result", SqlDbType.Int);
SQLCommand.ExecuteScalar();
int id = SQLCommand.Parameters["#result"].Value;
You can use either SCOPE_IDENTITY or ##IDENTITY
SCOPE_IDENTITY:
strSQL = "INSERT INTO Policies (...) VALUES (#vals....);SELECT SCOPE_IDENTITY()";
SQLCommand.CommandText = strSQL;
IdReturned = SQLCommand.ExecuteScalar();
##IDENTITY:
strSQL = "INSERT INTO Policies (...) VALUES (#vals....);SELECT ##Identity";
SQLCommand.CommandText = strSQL;
IdReturned = SQLCommand.ExecuteScalar();
For the differences between the two i recommend reading this article
If you do a INSERT INTO Policies() call first, in order to get the lastid, you could do something like this:
int lastId = 0;
using(SqlConnection Connection = new SqlConnection("(connection string)"))
{
string queryStatement =
"INSERT INTO dbo.Policies(fields) OUTPUT Inserted.LastID VALUES(....)";
using(SqlCommand Command = new SqlCommand(queryStatement, Connection))
{
Connection.Open();
lastId = Command.ExecuteScalar();
Connection.Close();
}
}
Use the OUTPUT ....... clause to return the newly inserted lastId.
Then go on and use that value in your main query.
Marc