Insert into 3 tables that are inter-dependent - asp.net

I have 3 tables-
1. Country (CountryName, CID (PK- AutoIncrement))
2. State (SID(PK- AutoIncrement), StateName, CID (FK to Country)
3. City (CityName, CID, SID (FK to State)
Now I need to insert only the name into the three tables with CountryName, StateName and CityName.. The IDs need to get updated.
How'd I do this?
Thanks,

you can use stored procedure to that inside the stored procedure you can first insert into the country table :
Insert into Country ( CountryName) VALUES (#CountryName)
DECLARE #cid as INTEGER = ##IDENTITY
then use SELECT ##IDENTITY in the secound insert like this :
Insert into State( StateName, cid ) values (#StateName, #cid)
DECLARE #SID as INTEGER = ##IDENTITY
and use the same in the third insert statment :
Insert into City ( CityName, CID,SID ) values (#CityName,#CID,#SID )
that is all what you need

If you would like to use linq to SQL
var country = new Dbml.Country();
country.Name = "countryname";
var state = new Dbml.State();
state.Country = country;
state.Name = "stateName"
var city = new Dbml.City();
city.State= state;
city.cityName = "cityName";
context.SubmitChanges();

Related

How to separate (split) string with comma in SQL Server stored procedure

I have a checkboxlist. The selected (checked) items are stored in List<string> selected.
For example, value selected is monday,tuesday,thursday out of 7 days
I am converting List<> to a comma-separated string, i.e.
string a= "monday,tuesday,thursday"
Now, I am passing this value to a stored procedure as a string. I want to fire query like:
Select *
from tblx
where days = 'Monday' or days = 'Tuesday' or days = 'Thursday'`
My question is: how to separate string in the stored procedure?
If you pass the comma separated (any separator) string to store procedure and use in query so must need to spit that string and then you will use it.
Below have example:
DECLARE #str VARCHAR(500) = 'monday,tuesday,thursday'
CREATE TABLE #Temp (tDay VARCHAR(100))
WHILE LEN(#str) > 0
BEGIN
DECLARE #TDay VARCHAR(100)
IF CHARINDEX(',',#str) > 0
SET #TDay = SUBSTRING(#str,0,CHARINDEX(',',#str))
ELSE
BEGIN
SET #TDay = #str
SET #str = ''
END
INSERT INTO #Temp VALUES (#TDay)
SET #str = REPLACE(#str,#TDay + ',' , '')
END
SELECT *
FROM tblx
WHERE days IN (SELECT tDay FROM #Temp)
Try this:
CREATE FUNCTION [dbo].[ufnSplit] (#string NVARCHAR(MAX))
RETURNS #parsedString TABLE (id NVARCHAR(MAX))
AS
BEGIN
DECLARE #separator NCHAR(1)
SET #separator=','
DECLARE #position int
SET #position = 1
SET #string = #string + #separator
WHILE charindex(#separator,#string,#position) <> 0
BEGIN
INSERT into #parsedString
SELECT substring(#string, #position, charindex(#separator,#string,#position) - #position)
SET #position = charindex(#separator,#string,#position) + 1
END
RETURN
END
Then use this function,
Select *
from tblx
where days IN (SELECT id FROM [dbo].[ufnSplit]('monday,tuesday,thursday'))
try this
CREATE FUNCTION Split
(
#delimited nvarchar(max),
#delimiter nvarchar(100)
) RETURNS #t TABLE
(
-- Id column can be commented out, not required for sql splitting string
id int identity(1,1), -- I use this column for numbering splitted parts
val nvarchar(max)
)
AS
BEGIN
declare #xml xml
set #xml = N'<root><r>' + replace(#delimited,#delimiter,'</r><r>') + '</r></root>'
insert into #t(val)
select
r.value('.','varchar(max)') as item
from #xml.nodes('//root/r') as records(r)
RETURN
END
GO
usage:
select * from tblx where days in (select val from dbo.split('monday,tuesday,thursday',','))
I think you want this
SELECT * FROM tblx where days in ('Monday','Tuesday','Thursday')
you can get it like this:
var a = "monday,tuesday,thursday";
var sql = string.Format("Select * from tblx where days IN ('{0}')", string.Join("','",a.Split(new[] {','})));
I face the same problem, and i try all the way but not get expected solution. Finally i did like follow. Try it hope it will work...
create Function [dbo].[Split]
(
#RowData NVARCHAR(MAX),
#SplitOn NVARCHAR(5)
)
RETURNS #RtnValue TABLE
(
Id INT IDENTITY(1,1),
Data NVARCHAR(100)
)
AS
BEGIN
DECLARE #Cnt INT
SET #Cnt = 1
WHILE (Charindex(#SplitOn,#RowData)>0)
BEGIN
INSERT INTO #RtnValue (data)
SELECT Data = ltrim(rtrim(Substring(#RowData,1,Charindex(#SplitOn,#RowData)-1)))
SET #RowData = Substring(#RowData,Charindex(#SplitOn,#RowData)+1,len(#RowData))
SET #Cnt = #Cnt + 1
END
INSERT INTO #RtnValue (data)
SELECT Data = ltrim(rtrim(#RowData))
RETURN
END
And in the store procedure put the code like that.
select #ActualTarget= count(*) from UpdateVisitDetails where CreatedBy IN (SELECT [DATA] FROM [dbo].[Split](#AllDATS,',' ))
I have same problem. I tried this.. and this was properly run
ALTER FUNCTION [dbo].[Split]
(
#List varchar(max),
#SplitOn nvarchar(5)
)
RETURNS #RtnValue table
(
Id int identity(1,1),
Value nvarchar(max)
)
AS
BEGIN
IF (len(#List) <=0)
Begin
Return
End
While (Charindex(#SplitOn,#List)>0)
Begin
Insert Into #RtnValue (value)
Select
Value = ltrim(rtrim(Substring(#List,1,Charindex(#SplitOn,#List)-1)))
Set #List = Substring(#List,Charindex(#SplitOn,#List)+len(#SplitOn),len(#List))
End
Insert Into #RtnValue (Value)
Select Value = ltrim(rtrim(#List))
Return
END
Run :
SELECT * FROM dbo.Split('Apple,Banana,Mango',',')
Output:

Insert into table from select query + variables values

I want to insert into the table tb2 (QuestionID, QuestionStem, UserID, ExamID) a set of rows selected randomly from table tb1 (QuestionID, QuestionStem) along with values for the two columns UserID, ExamID which are fixed for one insert query. I have tried this query in webmatrix, but I got an error that # should not be in this location in the insert query statment:
db.Query("INSERT INTO tb2 (QuestionID, QuestionStem, UserID, ExamID) SELECT QuestionID, QuestionStem, #UserID, #ExamID FROM tb2");
Any help is appreciated. I am using webmatrix 3.0 to build my app.
Note, UPDATE statement after insert will not work as there will be simultaneuos users and I want to present the selected row based on UserID and ExamID per user.
You can't accomplish your task with a single parameterized query in Webmatrix and, in my opinion, it's not a good solution create a query concatenating parameters.
A better alternative could be extract from table t1 the records you need and insert them one by one with a foreach loop:
#{
var userId = 25;
var examId = 32;
var sql1 = "SELECT TOP 10 QuestionID, QuestionStem FROM t1 ORDER BY NEWID()";
var sql2 = #"INSERT INTO tb2 (QuestionID, QuestionStem, UserID, ExamID)
VALUES (#0, #1, #2, #3)";
var db = Database.Open("yourDb");
var data = db.Query(sql1);
foreach (var row in data){
db.Execute(sql2, row.QuestionID, row.QuestionStem, userId, examId);
}
}
Edited
If performances are a real concern, maybe the best solution is to migrate data from Sql Server Compact to Sql Server Express.
In this environment you could create a Stored Procedure like
CREATE PROCEDURE AddQuestions #UserID int, #ExamID int
AS
INSERT INTO dbo.tb2 (QuestionID, QuestionStem, UserID, ExamID)
SELECT TOP 10 QuestionID, QuestionStem, #UserID AS UserID, #ExamID AS ExamID
FROM dbo.t2 ORDER BY NEWID()
GO
and recall it in WebMatrix:
#{
var userId = 14;
var examId = 16;
var db = Database.Open("yourDb");
var data = db.Execute("EXEC AddQuestions #UserID = #0, #ExamID = #1",
userId, examId);
}
If I understand you correctly, you could use numbered ordinals for the two parameters. Something like this, but setting the variables to use your data as appropriate of course:
var userId = 0;
var examId = 0;
db.Query("INSERT INTO tb2 (QuestionID, QuestionStem, UserID, ExamID) SELECT QuestionID, QuestionStem, #0, #1 FROM tb1", userId, examId);
You also mentioned you want the rows from tb1 to be selected randomly. You can achieve this by adding ORDER BY NEWID() to the end of the SELECT statement in your query:
db.Query("INSERT INTO tb2 (QuestionID, QuestionStem, UserID, ExamID) SELECT QuestionID, QuestionStem, #0, #1 FROM tb1 ORDER BY NEWID", userId, examId);
If you want to limit it to a number of rows only you can do (for example, with ten rows):
db.Query("INSERT INTO tb2 (QuestionID, QuestionStem, UserID, ExamID) SELECT TOP 10 QuestionID, QuestionStem, #0, #1 FROM tb1 ORDER BY NEWID", userId, examId);

How to pass concatenated value of drop down to stored proc as parameter

I have a drop down where in the values are concatenated from two columns of a table, now I will use the value of that drop down as a parameter to another stored procedure, is this possible? How will I do that?
This is my code
CREATE PROCEDURE [dbo].[Reassign]
#recordumber int
#employeeName
AS
BEGIN
UPDATE QR
SET QR.QAMemberID = #QAMemberID
FROM Roster AS QR
INNER JOIN TeamMaster S TM
ON QR.QAMemberID = TM.QAMemberID
WHERE QR.recordNumber = #recordumber
and qr.firstname, qr.lastname = #employeeName
END
and qr.firstname, qr.lastname = #employeeName I know this last piece of code is wrong... how can I do this the right way? Thank you...
Do not concatenate the values together in your code, but rather use a parameter for firstName and a parameter for lastName, like this:
CREATE PROCEDURE [dbo].[Reassign]
#recordumber int,
#firstName,
#lastName
AS
BEGIN
UPDATE QR
SET QR.QAMemberID = #QAMemberID
FROM Roster AS QR
INNER JOIN TeamMaster S TM
ON QR.QAMemberID = TM.QAMemberID
WHERE QR.recordNumber = #recordumber
and qr.firstname = #firstName, qr.lastname = #lastName
END
To use the value from your drop down you can use this in the code behind
if (myDropDown.SelectedIndex != 0)
{
var myData = myDropDown.SelectedValue;
// access Sproc and you can then pass myData
}
You can use qr.firstname + ' ' + qr.lastname = #employeeName if you concatenated that fields with space.
...
and qr.firstname + ' ' + qr.lastname = #employeeName
...
But it's better to pass two parameters into the procedure:
CREATE PROCEDURE [dbo].[Reassign]
#recordumber int
#firstname,
#lastname
AS
...
and qr.firstname = #firstname and qr.lastname = #lastname
...

Comparing data from 2 tables and display the result on a dropdownlist using LINQ

I have the 2 following tables: Country and Postal
I retrive all the countries in a DropDownAddCountry and i wan't by doing that to display all the postals belonging to the country in another dropdown (DropDownAddPostals).
The country table have a coulmn CountryID and postal also have a coulm CountryID. So i wan't the result to be based on match between CountryID and CountryID (from both tables):
My code look like this now (and it's not correct):
using (DB_Entities tt = new DB_Entities())
{
var sql = from q1 in tt.Country
join q2 in tt.Postal on q1.CountryID equals q2.CountryID
select new { q2.Postal1 };
if(sql != null)
{
DropDownAddPostal= sql.Postal1;
}
}
Cheers
Don't use anonymous types (especially if they are not necessary).
You can set the collection to your DropDownList with the DataSource-Property.
using (var tt = new DB_Entities())
{
var sql =
from q1 in tt.Country
join q2 in tt.Postal on q1.CountryID equals q2.CountryID
select q2.Postal1
DropDownAddPostal.DataSource = sql.ToList();
DropDownAddPostal.DataBind();
}

linq query with group

I'm having a table which contains userId, regBy, regDate and so many..
I need a out of regDate, regBy and count(userId).
How can a query this using LINQ..
From what I understand, you want to group by two fields, regDate and regBy. In that case, the select statement looks something like this:
var myQuery = from User myUser in myContext.Users
group myUser by new { regDate = myUser.regDate , regBy = myUser.regBy } into g
select new
{
regDate = g.Key.regDate,
regBy = g.Key.regBy,
Count = g.Count()
};

Resources