I want to define one stored procedure having 2 tables that insert into the first table and updates the second table. The first table contains the PostID and the PersonID, the second table contains postID and Counter. Would you please help me correct this one? I know this is not correct.
com.CommandText = #"CREATE PROCEDURE dbo.Facebook #PostID int,#PerosnalID int,
BEGIN
INSERT dbo.Like (PostID) VALUES (#PersonalID),
UPDATE dbo.Counter (Counter)
SET PostID = #value1
WHERE Counter = Sum #PersonalID
END";
Let's start and fix the procedure syntax:
com.CommandText = "CREATE PROCEDURE dbo.Facebook( #PostID int,#PersonalID int) AS "+
" INSERT dbo.[Like] (PostID) VALUES (#PersonalID); " +
" UPDATE C SET Counter = (SELECT COUNT(*) FROM dbo.[Like] WHERE PostId = #PersonalID)" +
" FROM dbo.Counter AS C " +
" WHERE C.PostID = #PersonalID ";
Related
I have this Table Data for my FullSummary Database:
I want to update ONLY the "Name, Price, and Total" for the HIGHEST Id of a selected Name.
If I select "random" the "random" with Id 52 should be the only one that will have the updated data.
I tried:
con.Open();
cmd.CommandText = "UPDATE FullSummary SET Name='" + addRiceTextBox.Text + "', Price='" + addPriceTextBox.Text + "', Total='" + newTotalEdit.Text + "' WHERE(Id, Name) IN(SELECT MAX(Id), Name FROM FullSummary GROUP BY Name)";
cmd.ExecuteNonQuery();
con.Close();
But it gave me this error:
I found the code here: select only rowwith highest id value if there are identical column values
And this one: How can I select the row with the highest ID in MySQL? only selects an item and not update it.
SQL Server doesn't support tuple comparison. So this
WHERE(Id, Name) IN (SELECT MAX(Id), Name FROM FullSummary ...)
Won't work. So you should use a scalar subquery like this (with parameters):
UPDATE FullSummary f
SET Price=#price, Total=#total
WHERE Id = (select max(ID) from FullSummary where name = #name)
Table A:
ID NAME SURNAME BRANCH
------------------------------------
1 Alma Amelie D
5 Brisa Broke C
Table B:
ID NAME SURNAME BRANCH Count
-------------------------------------------
New table B:
ID NAME SURNAME BRANCH Count
-------------------------------------------
1 Alma Amelie D 1
5 Brisa Broke C 1
I added table b to table a. I want the table to have a count of 1.
For example get count 2 when I want to make the second insert into the table. Get count 3 when I want to make the third insert into the table. I would like to define a variable from the master database and increase it as max + 1.
How can I do it? I moved the table, but I could not count. How can I do.
public void InsertTable()
{
"INSERT INTO" + tbl_B + "select ID,NAME,SURNAME,COUNT" + "FROM" TBL_A ;
.
.
}
I write sql code, then all you need is just calling that in your C# code.
frist run this in sql server on your databse
create proc checktableB
(
#id int
)
as
if EXISTS ( select ID,NAME,SURNAME,COUNT(*)as count FROM TBL_A where ID=#id)
begin
declare #I int;
set #I=(select COUNT(*) from tbl_A group by ID,NAME,SURNAME having ID=#id)+1
update tbl_B set COUNT=#I where ID=#id
end
else
begin
INSERT INTO tbl_B select ID,NAME,SURNAME,1 FROM TBL_A
end
GO
---===============================
Call this proc in your method in c#:
public void InsertTable(int _ID)
{
"exec checktableB #id="_ID //(any new id you want to insert or check )
}
"INSERT INTO" + tbl_B + "select ID,NAME,SURNAME,(select max(COUNT)+1 from tbl_a)" + "FROM" TBL_A ;
But it won't work with multiple simultaneous inserts. For that you should create a sequence if your db allows them. You will get gaps but a unique, sequential count.
I have a DataTable BonLivraison with a primary key that is a string with the format 2016/ + increment number. I used this code to generate this primary key:
SqlCommand cmdRow = new SqlCommand("select TOP(1) CodeBonLivraison from BonLivraison ORDER BY 1 DESC", con);
string LastCode = (string)cmdRow.ExecuteScalar();
string getID = LastCode.Split('/')[1];
int getIntID = Convert.ToInt32(getID);
numeroBonReceptionTextBox1.Text = DateTime.Now.Year.ToString() + "/" + (getIntID + 1).ToString();
This code generates primary keys normally 2016/1...2016/2....until 2016/10 it re-generates 2016/10 which is primary key violation.
So how modify this code to get last inserted key and get 2016/11...2016/12...
change your query to
select TOP(1) CodeBonLivraison
from BonLivraison
ORDER BY convert(int,
right(CodeBonLivraison, charindex('/', reverse(CodeBonLivraison )) - 1)
) DESC
Try something like this:
select TOP(1) CodeBonLivraison
from BonLivraison
ORDER BY CAST(SUBSTRING(CodeBonLivraison, 6, LEN(CodeBonLivraison ) - 5) as int) DESC
I'm trying to insert data from Table1 to Table2 on a button press from a C# web form. I've got it working with appending just the question numbers from Table1 to Table2 but I can't figure out how to add extra details to be added from the form. (DateStamp, user) etc
SqlConnection conn10000 = new SqlConnection(ConfigurationManager.ConnectionStrings["ESRConnectionString"].ConnectionString);
conn10000.Open();
string AppendQuestions = "INSERT INTO Table2 " +
" (StressQuestionNumber, StressQuestionnaireID, CreatedBy, CreateDate) VALUES( " +
"SELECT StressQuestionNumber " +
"FROM Table1, " +
"#StressQuestionnaireID, #CreatedBy, #CreateDate )";
SqlCommand com10000 = new SqlCommand(AppendQuestions, conn10000);
com10000.Parameters.AddWithValue("#StressQuestionnaireID", StressID);
com10000.Parameters.AddWithValue("#CreatedBy", Session["sesUserLogIn"]);
com10000.Parameters.AddWithValue("#CreateDate", DateTime.Now);
com10000.ExecuteScalar();
conn10000.Close();
Something like
INSERT INTO Table2
(
StressQuestionNumber, StressQuestionnaireID, CreatedBy, CreateDate
)
SELECT StressQuestionNumber, #StressQuestionnaireID, #CreatedBy, #CreateDate
FROM Table1
I am looking into rewriting a stored procedure that returns an output parameter inside my code. Why I am doing this is because I am wanting to have a local stored procedure instead of having to call the stored procedure from MSSQL.
Is this possible? If so, then how?
I have looked into LINQ to Entities and started to realize that there is so little control of the queries. I need to find more definitive info, but from working with real stored procedures and using multiple queries, having an actual stored procedure would be more efficient with large amounts (meaning hundreds of thousands) of records because of pre-built items included with MSSQL and SPs. I am using this question as a reference for a future project when we want to have small-scale data being transferred from the front end of the site instead of using stored procedures.
This link is what I used to write my raw SQL code. I am using the primitive calls so I can return string variables.
http://www.entityframeworktutorial.net/EntityFramework4.3/raw-sql-query-in-entity-framework.aspx
A rough draft of my stored procedure looks like this:
I am using // for legibility purposes when viewing this answer. Please use -- when using this code.
CREATE PROCEDURE [dbo].[spSomething]
#FirstName varchar(25),
#LastName varchar(25),
#UserID varchar(25),
#RentalManID varchar(25),
#BranchAreaNum varchar(25),
#ReturnVal varchar(1) = '0' output
WITH RECOMPILE
AS
BEGIN
SET NOCOUNT ON;
DECLARE #CheckTblUserAdded varchar(25)
DECLARE #CheckTblUser varchar(25)
// ReturnVal = 0 means it failed to add user to table
// ReturnVal = 1 means it succeded in adding user to table
// ReturnVal = 2 means the user has already been added to the table
// Search for user inside tblUserAdded
SELECT #CheckTblUserAdded = [Window ID] FROM dbo.tblUserAdded WHERE [Window ID] = #UserID AND
[Rentalman ID] = #RentalManID AND
[BranchAreaNum] = #BranchAreaNum AND
[FirstName] = #FirstName AND
[LastName] = #LastName
// Search for user inside tblUser
SELECT #CheckTblUser = [UserID] FROM dbo.tblUser WHERE [UserID] = #UserID AND
[RentalManID] = #RentalManID
// Add new user if not found in either tblUserAdded or tblUser
// and if the users windows id and rentalmanid are not the same
IF (ISNULL(#CheckTblUserAdded, '') = '') AND (ISNULL(#CheckTblUser, '') = '') AND (#UserID <> #RentalManID)
BEGIN
// Do something here
SELECT #ReturnVal = '1' // as success
END
// Record attempt of adding an existing user
ELSE
BEGIN
// Do something here
SELECT #ReturnVal = '2' // already exists
END
SELECT #ReturnVal
END
This is my raw SQL version of this inside my controller:
public ActionResult Create([Bind(Include="Window_ID,Rentalman_ID,BranchAreaNum,FirstName,LastName")] tblUserAdded tbluseradded)
{
if (ModelState.IsValid)
{
if (tbluseradded.Window_ID == tbluseradded.Rentalman_ID)
{
System.Diagnostics.Debug.WriteLine("The user should already have access since the user's Windows ID and RentalMan ID are the same. Contact IAUnit for help on the issue");
}
else
{
// Rewrite stored procedure in form of raw SQL
string returnVal = "0";
// This will check to see if a user has already been added to tblUser and tblUserAdded
string checkTblUserAdded = db.Database.SqlQuery<string>("SELECT [Window ID] FROM dbo.tblUserAdded WHERE " +
"[Window ID] = '" + tbluseradded.Window_ID + "' AND " +
"[Rentalman ID] = '" + tbluseradded.Rentalman_ID + "' AND " +
"[BranchAreaNum] = '" + tbluseradded.BranchAreaNum + "' AND " +
"[FirstName] = '" + tbluseradded.FirstName + "' AND " +
"[LastName] = '" + tbluseradded.LastName + "'").FirstOrDefault<string>();
string checkTblUser = db.Database.SqlQuery<string>("SELECT [UserID] FROM dbo.tblUser WHERE " +
"[UserID] = '" + tbluseradded.Window_ID + "' AND " +
"[RentalManID] = '" + tbluseradded.Rentalman_ID + "'").FirstOrDefault<string>();
// Add new user if not found in either tblUserAdded or tblUser
if (checkTblUser == null && checkTblUserAdded == null)
{
System.Diagnostics.Debug.WriteLine("We can add the user now! We did it!");
returnVal = "1";
// Do something here
}
else
{
System.Diagnostics.Debug.WriteLine("This user already has access");
returnVal = "2";
// Do something here
}
System.Diagnostics.Debug.WriteLine("The return value is: " + returnVal);
System.Diagnostics.Debug.WriteLine("Please break here!");
db.SaveChanges();
}
return RedirectToAction("Index");
}
return View(tbluseradded);
}
I am sure there is a better way of coding this by putting the actual raw SQL in a Data Access Layer, but I am using this for information purposes only.