Using Select statement for Insert Statement Value - c#

Can you please help me with this statement, i am trying to retrieve data using SELECT statement and use the date in the INSERT statement.
I want to use the data retrieved for ProfileId Value.
// Get the UserId of the just-added user
MembershipUser currentUser = Membership.GetUser();
Guid currentUserId = (Guid)currentUser.ProviderUserKey;
// Insert a new record into UserPro
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string insertSql = "INSERT INTO User_Friend(ProfileId1, ProfileId) VALUES(#FriendProfileId) SELECT ProfileId FROM User_Profile WHERE UserId = (#UserId)";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(insertSql, myConnection);
myCommand.Parameters.AddWithValue("#FriendProfileId", Request.QueryString["ProfileId"].ToString());
myCommand.Parameters.AddWithValue("#UserId", currentUserId);
myCommand.ExecuteNonQuery();
myConnection.Close();
}
How do I use the SELECT result as the ProfileId Value.

The insert statement should be
INSERT INTO User_Friend(ProfileId1, ProfileId)
VALUES ( #FriendProfileId,
(SELECT ProfileId FROM User_Profile WHERE UserId = #UserId))
or maybe SELECT TOP(1) ProfileId to make sure you will never get more than 1 value.

The insert SQL should be:
string insertSql = "INSERT INTO User_Friend(ProfileId1, ProfileId) SELECT #FriendProfileId, ProfileId FROM User_Profile WHERE UserId = (#UserId)";
You just include the variables directly in the SELECT statement in the position corresponding to the column name.

Related

C# Check if email already exists

How do I modify this registration code so it checks if email entered already exists in the database?
I already have a query written for it, but I don't know how to implement it
[HttpPost("Register")]
public async Task<ActionResult<User>> Register(UserDto request, Guid guid)
{
string query = #"
insert into dbo.Users(UserID,Name,Email,PasswordHash,PasswordSalt)
values (#UserID,#Name,#Email,#PasswordHash,#PasswordSalt)
";
string emailValidationQuery = #"SELECT * FROM dbo.Users WHERE Email = #Email";
CreatePasswordHash(request.Password, out byte[] passwordHash, out byte[] passwordSalt);
string psw = PasswordHash(request.Password);
Guid guid1 = Guid.NewGuid();
guid = guid1;
user.UserID = guid;
user.Username = request.Username;
user.Email = request.Email;
user.PasswordHash = Encoding.UTF8.GetBytes(psw);
user.PasswordSalt = passwordSalt;
DataTable table = new DataTable();
string sqlDataSource = _configuration.GetConnectionString("ContactAppCon");
SqlDataReader myReader;
using (SqlConnection myCon = new SqlConnection(sqlDataSource))
{
myCon.Open();
using (SqlCommand myCommand = new SqlCommand(query, myCon))
{
myCommand.Parameters.AddWithValue("#UserID", Guid.NewGuid());
myCommand.Parameters.AddWithValue("#Name", request.Username);
myCommand.Parameters.AddWithValue("#Email", request.Email);
myCommand.Parameters.AddWithValue("#PasswordHash", psw);
myCommand.Parameters.AddWithValue("#PasswordSalt", passwordSalt);
myReader = myCommand.ExecuteReader();
table.Load(myReader);
myReader.Close();
myCon.Close();
}
}
return Ok(user);
}
Try something like below (open and dispose the connections properly)
string emailValidationQuery = #"SELECT Count(*) FROM dbo.Users WHERE Email = #Email";
....
using SqlCommand command = new SqlCommand(emailValidationQuery, myCon);
int count = (Int32) command.ExecuteScalar();
if(count > 0)
return new User() // or whatever you required
Why not a single statement:
INSER INTO dbo.Users (UserID, Name, Email, ...)
VALUES (#UserID, #Name, #Email, ...)
WHERE NOT EXISTS
(
SELECT 0
FROM dbo.Users WITH (SERIALIZABLE, UPDLOCK)
WHERE Email = #Email
);
If this affects 0 rows (you can check with ##ROWCOUNT), then the e-mail already existed (and maybe you should run an update instead in that case, but it's not clear from the question) or the insert failed for some other reason (which you can check with simple try/catch patterns).
And you can prevent race conditions and avoid costly exceptions by doing it a little differently:
BEGIN TRANSACTION;
IF NOT EXISTS
(
SELECT 0 FROM dbo.Users WITH (SERIALIZABLE, UPDLOCK)
WHERE Email = #Email
)
BEGIN
INSERT ...
END
ELSE
BEGIN
-- UPDATE? RAISERROR? Again requirements aren't clear.
END
COMMIT TRANSACTION;
Don't go for simple or expensive when correct and more efficient are better.

SQL Server query is not returning any rows

I am trying to read a single column from a single row. After executing the query no rows are returned but there are fields.
When I look at the reader HasRows is false but the field count is 1.
string sql = "select userid from aspnet_Membership where loweredemail = '#email'";
SqlCommand sqlCommand = new SqlCommand(sql, THOGConnection);
string emailAddress = (string)account["ree_thogemail"];
emailAddress = emailAddress.ToLower();
sqlCommand.Parameters.AddWithValue("#email", emailAddress);
SqlDataReader reader = sqlCommand.ExecuteReader();
while(reader.Read())
{
userId = (Guid)reader["userid"];
}
If I select all columns in the row then the field count is 21 but there are still no rows.
Why am I not returning any rows?
Thanks, Gary
You don't need to use ' around #email. Use :
string sql = "select userid from aspnet_Membership where loweredemail = #email"
Actually it returns no value, because there is no record with loweredemail = '#email' while there is record with for example loweredemail = 'someone#example.com'.
When using parameters, single quotes are not needed.
There is syntax error in your sql query:
string sql = "select userid from aspnet_Membership where loweredemail = '#email'";
should be like the following
string sql = "select userid from aspnet_Membership where loweredemail = #email";

Read Id of last inserted

I have been through everything for a couple weeks now only to find statements working at the database level. Below is my code and I feel that I am very near the answer but keep getting -1 returned from SCOPE_IDENTITY(). Customer_Name is saving to the table just fine along with the auto increment. I just need the Customer_ID so that I can place it in the Customer_Address table for the one to many identification of the address to the customer.
Thanks in advance for your help.
if (customer_ID == "")
{
// add new customer
string SQL = "INSERT INTO Customer (Customer_Name) VALUES (#customer_Name)";
SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
sqlCommand.Parameters.Add("#customer_Name", SqlDbType.VarChar, 100).Value = customer_Name;
// get last inserted Customer_ID
string SQL_customerId = "SELECT SCOPE_IDENTITY()";
SqlCommand sqlCommand_customerId = new SqlCommand(SQL_customerId, sqlConnection);
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
sqlCommand_customerId.ExecuteNonQuery();
// string SQL_ = "SELECT Customer_ID FROM Customer";
// SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
// int maxId = Convert.ToInt32(sqlCommand.ExecuteScalar());
sqlConnection.Close();
}
You need to have the SCOPE_IDENTITY within the same transaction as your insert. The following should help you.
string SQL = "INSERT INTO Customer (Customer_Name) VALUES (#customer_Name); SELECT Customer_Id FROM Customer WHERE Customer_Id = SCOPE_IDENTITY();";
SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
sqlCommand.Parameters.Add("#customer_Name", SqlDbType.VarChar, 100).Value = customer_Name;
sqlConnection.Open();
int id = (int) sqlCommand.ExecuteScalar();
try something like this..
Output clause will help you to get the inserted value and with that we can insert into another temp or physical table. This is just an idea to your question
CREATE TABLE customer
(
id INT IDENTITY(1, 1),
addres VARCHAR(500)
)
CREATE TABLE customeraddrs
(
custid INT
)
INSERT INTO customer
output inserted.id
INTO customeraddrs
VALUES ('a'),
('b')
SELECT *
FROM customer
SELECT *
FROM customeraddrs

How to use SqlDataReader to retrieve information from database, c#

I need to access a variable in my SQL database, along with a username which is already implemented properly. I query the database using this statement:
private const string _getUserByUsernameQuery = #"
SELECT
[User].[username]
FROM
[User] WITH (NOLOCK)
INNER JOIN [Company] WITH (NOLOCK)
ON [User].[companyId] = [Company].[id]
WHERE
[User].[username] = #username
AND [User].[password] = #password";
Then connect to the database and access the username:
using (SqlConnection connection = new SqlConnection(SQLConfiguration.ConnectionString))
{
SqlCommand command = new SqlCommand(_getUserByUsernameQuery, connection);
command.Parameters.AddWithValue("#username", username);
command.Parameters.AddWithValue("#password", password);
try
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
Username = Convert.ToString(reader["username"]);
//CompanyId = Convert.ToString(reader["companyId"]);
lblUsername = Username;
//lblCompanyId = CompanyId;
Debug.WriteLine("Testing2::");
Debug.WriteLine(lblUsername);
//Debug.WriteLine(lblCompanyId);
}
}
}
catch (Exception)
{
if(connection.State == System.Data.ConnectionState.Open)
connection.Close();
}
}
In the if statement where I set reader["username"] equal to Username, I output Username using debug and the value is correct. What i have in comments relating to CompanyId is what I want to do, but was unable. Doing so doesn't cause errors, but it does ignore the entire statement (even the Username variable which works otherwise). based on my query string, how can I access the variable companyId?
In your _getUserByUsernameQuery you are only selecting the username field. Make sure that fields that you want to read from reader[...] are present in your select statement.
Looks like you need to add company id to your select statement to be able to retrieve it:
private const string _getUserByUsernameQuery = #"
SELECT
[User].[username], [User].[companyId]
FROM
[User] WITH (NOLOCK)
INNER JOIN [Company] WITH (NOLOCK)
ON [User].[companyId] = [Company].[id]
WHERE
[User].[username] = #username
AND [User].[password] = #password";

In c#, how to assign a sql query result within a variable?

SqlConnection connection = new SqlConnection(connString.ToString());
string select = "SELECT (CASE WHEN MAX(page_no) IS NULL THEN 1 ELSE MAX(page_no)+1 END) FROM dbo.BOOK";
string insert = "INSERT INTO dbo.BOOK (book_id,select) VALUES (121,4)";
SqlCommand sqlCommand = new SqlCommand(insert,connection);
insert.ExecuteNonQuery();
Here I got exception where the insert contains invalid string select.
Please tell me how assign sub query within the insert?
you cannot use a select statement like this
if you want to use a sub query it has to be in single statement
but in above statement you write in different different statement for selection
and insert query .
so cmd.ExecuteNonquery() execute only insert text statement so SQL engine unable to find SELECT(and SELECT is a Reserved keyword) so it gives you a error
if you go with subquery try this
SqlConnection connection = new SqlConnection(connString.ToString());
string select = "SELECT 121, (CASE WHEN MAX(page_no) IS NULL THEN 1 ELSE MAX(page_no)+1 END) FROM dbo.BOOK";
string insert = "INSERT INTO dbo.BOOK (book_id,[select]) "+select;
SqlCommand sqlCommand = new SqlCommand(insert,connection);
sqlCommand.ExecuteNonQuery();
Your query results will return a DataTable. So use a DatAdapter to fill a DataTable.
You are doing it wrong, you have to Execute query on SQLCommand object not on string object try this
using(SqlConnection connection = new SqlConnection(connString.ToString())){
string insert = "Insert Query";
using (SqlCommand sqlCommand = new SqlCommand(insert,connection))
{
con.Open();
int i = sqlCommand.ExecuteNonQuery();
}
}
Update:
var selectQuery = "SELECT (CASE WHEN MAX(page_no) IS NULL THEN 1 ELSE MAX(page_no)+1 END) FROM dbo.BOOK";
var insertQuery = string.format("INSERT INTO dbo.BOOK (book_id,{0}) VALUES (121,4)",selectQuery);

Categories