asp.net multiple table update statement - c#

I need to turn this query into an update statement. I will have to update the values from fields. Everything is already in place but the update statement.
Here is the select version of the query:
SELECT i.GoLiveDate, i.FirstBonusRun, i.TechFName, i.TechLName, i.TechEmail, i.TechPhone, i.WebISPFName, i.WebISPLName,
i.WebISPEmail, i.WebISPPhone, i.FullFillFName, i.FullFillLName, i.FullFillEmail, i.FullFillPhone, d.FName,
d.LName, d.HomePhone, d.Email
FROM NC_Information i
INNER JOIN Distributor d
ON d.DistID = i.ClientID
WHERE clientID = #value
Is it possible to update two different tables from within the same query?
Here is the code I have so far:
public void Update (int ClientID)
{
using ( var conn = new SqlConnection( GeneralFunctions.GetConnectionString() ) )
using ( var cmd = conn.CreateCommand() )
{
conn.Open();
cmd.CommandText =
#"SELECT i.GoLiveDate, i.FirstBonusRun, i.TechFName, i.TechLName, i.TechEmail, i.TechPhone, i.WebISPFName, i.WebISPLName,
i.WebISPEmail, i.WebISPPhone, i.FullFillFName, i.FullFillLName, i.FullFillEmail, i.FullFillPhone, d.FName,
d.LName, d.HomePhone, d.Email
FROM NC_Information i
INNER JOIN Distributor d
ON d.DistID = i.ClientID
WHERE clientID = #value";
cmd.Parameters.AddWithValue( "#value", ClientID );
cmd.ExecuteNonQuery();
}
}

You can't update multiple tables in one statement, but you can use a transaction to make sure that the updates are contingent upon one another:
BEGIN TRANSACTION
UPDATE SomeTable
SET SomeColumn = 'Foo'
WHERE SomeID = 123
UPDATE AnotherTable
SET AnotherColumn = 'Bar'
WHERE AnotherID = 456
COMMIT

I think, you cannot directly do the update on two tables. But you can Optimize the query.
How?
OUTPUT keyword in Insert/Update/Delete Statement
The first Update Statement's Select Data(filtered data) can be reused using the below mentioned example.
CREATE TABLE #table1
(
id INT,
employee VARCHAR(32)
)
go
INSERT INTO #table1 VALUES
(1, 'name1')
,(2, 'name2')
,(3, 'name3')
,(4, 'name4');
GO
DECLARE #GuestTable TABLE
(
id INT,
employee VARCHAR(32)
);
update #table1
Set id = 33
OUTPUT inserted.* INTO #GuestTable
Where id = 3
The Data in the '#GuestTable' Table is filtered data and can be
reused.
select * from #GuestTable
drop table #table1

Alternatively, you can create a dataset with two datatables, and let the tableadaptermanager manage the updates.

Related

TSQL generating update statement for table based on condition

How to generate update statement on the whole table with some condition ? For example I have table
and I would like to specify date (for this example '3/16/2016') and generate something like following Update
UPDATE TableName SET ColumnValue = 30 AND ModifiedDate = '2016-03-17' WHERE Id = 2
If there will be more changes after specified date, I would like to generate all the updates for these changes.
Is there some easy solution or I have to script all this by some customized C# script ?
If you have 2 identical tables and need to update one of the tables based on changes happed after a particular timestamp (#Date) in another table then you can use below query.
UPDATE T1
SET T1.ColumnValue=T2.ColumnValue,T1.ModifiedDate=T2.ModifiedDate
FROM Table1 T1 inner join Table2 T2 on T1.ID=T2.ID
WHERE T2.ModifiedDate>=#Date
If you just want to generate update statements, you could do something like this:
declare #afterDate date = '20160316';
select update_statements = 'update table t set columnvalue = '
+convert(varchar(10),columnvalue)
+', modifieddate = '''
+replace(convert(varchar(10),modifieddate,120),'-','')+''''
+' where id = '+convert(varchar(10),id)+';'
from t
where modifieddate > #afterdate;
rextester demo: http://rextester.com/MZQ68677
returns:
+------------------------------------------------------------------------------+
| update_statements |
+------------------------------------------------------------------------------+
| update table t set columnvalue = 30, modifieddate = '20160317' where id = 2; |
+------------------------------------------------------------------------------+
This gives the trigger to track all the updates for a table. Based on table structure you can add required columns in the tracking table.
CREATE TABLE EMP(ID int, NAME VARCHAR(20), SALARY MONEY)
CREATE TABLE TrackUpdate (Id int identity, updatestmt varchar(500), DateCreated datetime)
GO
INSERT INTO EMP
VALUES
(1, 'A', 10),(2, 'E',40 ),(3,'B',5),(4,'F',40),(5,'I',50)
GO
ALTER TRIGGER TR_EMP ON EMP
INSTEAD OF UPDATE
AS
BEGIN
declare #Name varchar(10)
declare #Salary MONEY
SELECT #Name=Name,#Salary=Salary FROM inserted
insert into TrackUpdate values ('update Emp SET E.Name='''+#Name+''', '+'E.Salary='+CAST(#Salary as varchar(20)),getdate())
update E SET E.Name=I.Name, E.Salary=I.Salary
FROM EMP E inner join inserted I on I.ID=E.ID
END
update EMP set Name='D' where ID=4
select updatestmt from TrackUpdate
--drop table EMP
--drop table TrackUpdate

Create a temporary table and then Select

I have the following problem in an WPF application written in c#. I need to create some temporary tables on an sql server, do some joins from within the app an then select from the joined table. In the statistical language R I simply create two SQL Queries (one containing the #tables and one with the final select statement from a merge of several #tables) and execute them one after another. Doing the query in just one Query only returns NULL after the #temp tables have been created.
This is SQL statement #1:
DECLARE #from_time Date;
DECLARE #to_time Date;
CREATE TABLE #temp1
(
person_id float,
first_name varchar(100),
othercols...
)
INSERT INTO #temp1
SELECT DISTINCT
person_id, first_name, ...
FROM
campus.v_exam_registration_context context
FULL JOIN
campus.v_exam_timetable time
ON
CAST(context.examination_date AS DATETIME) = time.timetable_date
AND
context.examination_time_from = time.time_from
AND
context.examination_time_to = time.time_to
CREATE TABLE #temp2
(
exam_event_id float,
person_id float,
othercols...
)
INSERT INTO #temp2
SELECT DISTINCT
exam_event_id, person_id, excused, excused_reason, missed, modify_date, study_id, study_name,
person_exam_id, exam_in_course_id, subject, subject_unicode, personal_exam_no, exam_points, grade_description
FROM
campus.v_person_exam exam
WHERE
exam.person_id
IN
(
SELECT
#temp1.person_id
FROM
#temp1
WHERE
#temp1.attempt_counter > 1
AND
#temp1.timetable_date > #from_time
AND
#temp1.timetable_date < #to_time
)
CREATE TABLE #temp3
(
person_id float,
first_name varchar(100),
)
INSERT INTO #temp3
SELECT
#temp2.person_id, first_name, last_name, matriculation_number, attempt_counter, timetable_date, examination_date, semester, course_number, course_name,
exam_name, exam_type, component_name, course_area, module_number, module_name, credits,
FROM
#temp2
LEFT JOIN
#temp1
ON
#temp2.person_id = #temp1.person_id
AND
#temp2.exam_event_id = #temp1.exam_event_id
WHERE
#temp1.course_name IS NOT NULL
And this is #2:
SELECT DISTINCT T1.*
FROM
#temp3 T1
INNER JOIN
(
SELECT *
FROM
#temp3
WHERE
#temp3.attempt_counter > 1
AND
#temp3.exam_points > 4
AND
#temp3.timetable_date > #from_time
AND
#temp3.timetable_date < #from_time
) as T2
ON
T1.person_id = T2.person_id
AND
T1.exam_name = T2.exam_name
ORDER BY T1.last_name ASC, T1.course_name DESC, T1.timetable_date ASC
But now I'm required to translate the R Script into a standalone exe-file.
Here is my code block in c#:
private void queryButton_Click(object sender, RoutedEventArgs e)
{
List<Student> temp = new List<Student>();
string pass = #pass_box.Password;
string dsn = "CampusNet";
String ConnectionString =
"DSN=" + dsn + ";" +
"UID=" + uid + ";" +
"PWD=" + pass;
OdbcConnection conn = new OdbcConnection(ConnectionString);
using (conn)
{
if (conn.State.ToString() == "Open")
{
conn.Close();
}
try
{
conn.Open();
var command = new OdbcCommand(sqlcommand, conn); \\sqlcommand is read from a textfile
command.Parameters.AddWithValue("#from_time", from_time);
command.Parameters.AddWithValue("#to_time", to_time);
command.CommandTimeout = 120;
var resultCommand = command.ExecuteNonQuery();
var query = new OdbcCommand(sqlquery, conn); \\sqlquery is read from a textfile
query.Parameters.AddWithValue("#from_time", from_time);
query.Parameters.AddWithValue("#to_time", to_time);
var resultQuery = query.ExecuteReader();
Results_Box.AppendText(resultQuery.HasRows.ToString());
while (resultQuery.Read())
{
temp.Add(new Student{
name = !result.IsDBNull(3) ? result.GetString(3) : null
});
Results_Box.AppendText("Test"); \\only for testing purposes, works if I select from existing table
}
resultQuery.Close();
results = temp;
Results_Box.Document.Blocks.Add(new Paragraph(
new Run("There are " + temp.Count().ToString() + " Hits")));
System.Windows.Forms.MessageBox.Show("Connected");
conn.Close();
}
catch (Exception E)
{
Results_Box.Document.Blocks.Add(new Paragraph(new Run("Connection failed")));
Results_Box.Document.Blocks.Add(new Paragraph(new Run(E.ToString())));
}
}
}
I'm new to c#, so it seems that the first query is executed but deleted immediately afterwards and the second select statement returns 0 hits. If I select from non-temporary tables everything works fine. Since the first query has a duration approximately equal to the respective R-Query (25 sec), I suspect that the first one is correctly executed, but immediately deleted or the second query starts before the first is finished. Creating one combined query does not work neither in R nor in c#. I would like to stick to temporary tables rather than using ##tables, if possible.
Is there a special method to use for creating temp tables in c#? conn.open() is open during the whole runtime of using (conn){...} ?

How to i get result based on ids list passed as a varchar?

I am passing ids list as a varchar(500) and based upon that ids records are required.My sql code is
declare #Ids varchar(500) = '12964,12965,12966'
select *
from tblBooks
where BookID in (#Ids)
where BookID is varchar(50).Number of Ids can be 100.Converting #Ids into int gives following error
Conversion failed when converting the varchar value
'12964,12965,12966' to data type int
How do i find result as #Id are not converted into Int.
Use a table variable:
DECLARE #Ids TABLE (ID INT);
INSERT #Ids VALUES (12964),(12965),(12966);
SELECT *
FROM tblBooks
WHERE BookID in (SELECT ID FROM #Ids);
If you need to pass this to a procedure then you can use a table valued parameter:
CREATE TYPE dbo.ListOfInt AS TABLE (ID INT);
GO
CREATE PROCEDURE dbo.GetBooks #IDs dbo.ListOfInt READONLY
AS
BEGIN
SELECT *
FROM tblBooks
WHERE BookID in (SELECT ID FROM #Ids);
END
GO
DECLARE #IDs dbo.ListofInt;
INSERT #Ids VALUES (12964),(12965),(12966);
EXECUTE dbo.GetBooks #Ids;
Or From c#
var table = new DataTable();
table.Columns.Add("ID", typeof(int));
// ADD YOUR LIST TO THE TABLE
using (var connection = new SqlConnection("Connection String"))
using (var command = new SqlCommand("dbo.GetBooks", connection))
{
command.CommandType = CommandType.StoredProcedure;
var param = new SqlParameter("#Ids", SqlDbType.Structured);
param.TypeName = "dbo.ListofInt";
param.Value = table;
command.Parameters.Add(table);
connection.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
// do something
}
}
}
Once the TYPE is in place, you don't even need to use a stored procedure. You can simply call a normal query:
using (var connection = new SqlConnection("Connection String"))
using (var command = new SqlCommand("SELECT * FROM tblBooks WHERE BookID IN (SELECT ID FROM #IDs)", connection))
{
var param = new SqlParameter("#Ids", SqlDbType.Structured);
param.TypeName = "dbo.ListofInt";
param.Value = table;
command.Parameters.Add(table);
connection.Open();
// ETC
}
Doing the split in c# using String.Split() and passing the list to SQL will be more efficient than any approach that does the split in SQL
You can write the query as this:
declare #Ids varchar(500) = '12964,12965,12966'
select *
from tblBooks
where ','+cast(BookID as varchar(500))+',' like '%,'+#Ids+',%';
But you don't want to do that because the performance is bad -- the query cannot use indexes.
Three other options. Use dynamic SQL and plug the list directly into the query. Or use a split function to split the string. Or use a table variable:
declare #ids table (id int);
insert into #ids(id)
select 12964 union all select 12965 union all select 12966;
select b.*
from tblBooks b
where b.BookId in (select id from #ids);
This won't work. SQL Server does not split strings for you implicitly and there is no built in string split function in SQL Server either.
If you are driving this via C# you can use Table value parameters. You can also pass your query through Dapper-Dot-Net which will automatically parameterize an "In" query.
If you really must do this in T-SQL, you can also use a string splitting logic here is a relatively concise one.
SELECT i.value('./text()[1]', 'int') [id] into #ids
FROM( values(CONVERT(xml,'<r>' + REPLACE(#Ids+left(##dbts,0),',','</r><r>') + '</r>')) ) a(_)
CROSS APPLY _.nodes('./r') x(i)
select *
from tblBooks a
join #ids i on i.id = a.bookId
Create this function:
CREATE FUNCTION [dbo].[SplitDelimiterString] (#StringWithDelimiter VARCHAR(8000), #Delimiter VARCHAR(8))
RETURNS #ItemTable TABLE (Item VARCHAR(8000))
AS
BEGIN
DECLARE #StartingPosition INT;
DECLARE #ItemInString VARCHAR(8000);
SELECT #StartingPosition = 1;
--Return if string is null or empty
IF LEN(#StringWithDelimiter) = 0 OR #StringWithDelimiter IS NULL RETURN;
WHILE #StartingPosition > 0
BEGIN
--Get starting index of delimiter .. If string
--doesn't contain any delimiter than it will returl 0
SET #StartingPosition = CHARINDEX(#Delimiter,#StringWithDelimiter);
--Get item from string
IF #StartingPosition > 0
SET #ItemInString = SUBSTRING(#StringWithDelimiter,0,#StartingPosition)
ELSE
SET #ItemInString = #StringWithDelimiter;
--If item isn't empty than add to return table
IF( LEN(#ItemInString) > 0)
INSERT INTO #ItemTable(Item) VALUES (#ItemInString);
--Remove inserted item from string
SET #StringWithDelimiter = SUBSTRING(#StringWithDelimiter,#StartingPosition +
LEN(#Delimiter),LEN(#StringWithDelimiter) - #StartingPosition)
--Break loop if string is empty
IF LEN(#StringWithDelimiter) = 0 BREAK;
END
RETURN
END
Then call it like this:
declare #Ids varchar(500) = '12964,12965,12966'
select *
from tblBooks
where BookID in (SELECT * FROM dbo.SplitDelimiterString(#ids,','))
one way is to cast int to varchar. many other ways....
select *
from tblBooks
where CAST(BookID as varchar(50)) in (#Ids)
related: Define variable to use with IN operator (T-SQL)

Parameters to the EXISTS clause in a stored procedure

I have a table DEPT, which holds 2 columns - ID, NAME.
A search form is presented with the IDs from the DEPT table and the user can chose any number of IDs and submit the form, to get the related NAMEs.
Clarification/Inputs:
I don't want to build a dynamic query - its not manageable.
I prefer a stored procedure using table-valued parameters
Any other solutions to proceed?
NOTE:
This example is simple with 1 table - in real life, I have to deal with more than 6 tables!
Thanks for any suggestions
CREATE TYPE dbo.DeptList
AS TABLE
(
ID INT
);
GO
CREATE PROCEDURE dbo.RetrieveDepartments
#dept_list AS dbo.DeptList READONLY
AS
BEGIN
SET NOCOUNT ON;
SELECT Name FROM dbo.table1 WHERE ID IN (SELECT ID FROM #dept)
UNION ALL
SELECT Name FROM dbo.table2 WHERE ID IN (SELECT ID FROM #dept)
-- ...
END
GO
Now in your C# code, create a DataTable, fill it in with the IDs, and pass it in to the stored procedure. Assuming you already have a list called tempList and the IDs are stored in id:
DataTable tvp = new DataTable();
tvp.Columns.Add(new DataColumn("ID"));
foreach(var item in tempList)
{
tvp.Rows.Add(item.id);
}
using (connObject)
{
SqlCommand cmd = new SqlCommand("StoredProcedure", connObject);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter tvparam = cmd.Parameters.AddWithValue("#dept_list", tvp);
tvparam.SqlDbType = SqlDbType.Structured;
...
}
You can also use a split function. Many exist, this is the one I like if you can guarantee that the input is safe (no <, >, & etc.):
CREATE FUNCTION dbo.SplitInts_XML
(
#List VARCHAR(MAX),
#Delimiter CHAR(1)
)
RETURNS TABLE
AS
RETURN
(
SELECT Item = y.i.value('(./text())[1]', 'int')
FROM
(
SELECT x = CONVERT(XML, '<i>'
+ REPLACE(#List, #Delimiter, '</i><i>') + '</i>').query('.')
) AS a
CROSS APPLY x.nodes('i') AS y(i)
);
GO
Now your procedure can be:
CREATE PROCEDURE dbo.RetrieveDepartments
#dept_list VARCHAR(MAX)
AS
BEGIN
SET NOCOUNT ON;
;WITH d AS (SELECT ID = Item FROM dbo.SplitInts(#dept_list, ','))
SELECT Name FROM dbo.table1 WHERE ID IN (SELECT ID FROM d)
UNION ALL
SELECT Name FROM dbo.table2 WHERE ID IN (SELECT ID FROM d)
-- ...
END
GO

SQL Server: Check if Child Rows Exist

I am working on a web application where there are many tables but two will suffice to illustrate my problem:
User
Order
Let us say that the User table has a primary key "UserID", which is a foreign key in the Order table called "CreatedBy_UserID".
Before deleting a User, I would like to check if the Order table has a record created by the soon-to-be deleted user.
I know that a SqlException occurs if I try to delete the user but let us say that I want to check beforehand that the Order table does not have any records created by this user? Is there any SQL code which I could run which will check all foreign keys of a table if that row is being referenced?
This for me is generally useful code as I could remove the option for deletion altogether if it can be detected that the user exists in these other tables.
I don't want a simple query (SELECT COUNT(*) FROM Order WHERE CreatedBy_UserID == #userID) because this will not work if I create another foreign key to the Order table. Instead I want something that will traverse all foreign keys.
Can this be done?
Below is code for an sp that I've used in the past to perform this task (please excuse the indenting):
create proc dbo.usp_ForeignKeyCheck(
#tableName varchar(100),
#columnName varchar(100),
#idValue int
) as begin
set nocount on
declare fksCursor cursor fast_forward for
select tc.table_name, ccu.column_name
from
information_schema.table_constraints tc join
information_schema.constraint_column_usage ccu on tc.constraint_name = ccu.constraint_name join
information_schema.referential_constraints rc on tc.constraint_name = rc.constraint_name join
information_schema.table_constraints tc2 on rc.unique_constraint_name = tc2.constraint_name join
information_schema.constraint_column_usage ccu2 on tc2.constraint_name = ccu2.constraint_name
where tc.constraint_type = 'Foreign Key' and tc2.table_name = #tableName and ccu2.column_name = #columnName
order by tc.table_name
declare
#fkTableName varchar(100),
#fkColumnName varchar(100),
#fkFound bit,
#params nvarchar(100),
#sql nvarchar(500)
open fksCursor
fetch next from fksCursor
into #fkTableName, #fkColumnName
set #fkFound = 0
set #params=N'#fkFound bit output'
while ##fetch_status = 0 and coalesce(#fkFound,0) <> 1 begin
select #sql = 'set #fkFound = (select top 1 1 from [' + #fkTableName + '] where [' + #fkColumnName + '] = ' + cast(#idValue as varchar(10)) + ')'
print #sql
exec sp_executesql #sql,#params,#fkFound output
fetch next from fksCursor
into #fkTableName, #fkColumnName
end
close fksCursor
deallocate fksCursor
select coalesce(#fkFound,0)
return 0
end
This will select a value of 1 if a row has any foreign key references.
The call you would need would be:
exec usp_ForeignKeyCheck('User','UserID',23)
There is no clean way to iterate through all FK columns where multiple exist. You'd have to build some dynamic SQL to query the system tables and test each in turn.
Personally, I wouldn't do this. I know what FKs I have: I'll test each in turn
...
IF EXISTS (SELECT * FROM Order WHERE CreatedBy_UserID == #userID)
RAISERROR ('User created Orders ', 16, 1)
IF EXISTS (SELECT * FROM Order WHERE PackedBy_UserID == #userID)
RAISERROR ('User packed Orders', 16, 1)
...
You wouldn't dynamically iterate through each property of some user object and generically test each one would you? You'd have code for each property
This code will give you a list of the foreign keys which are defined for a specifit table:
select distinct name from sys.objects
where object_id in ( select constraint_object_id from sys.foreign_key_columns as fk
where fk.Parent_object_id = (select object_id from sys.tables
where name = 'tablename') )
You can use transaction to check it.
I know it seems like stone ax, but it working fast and stable.
private bool TestUser(string connectionString, int userID)
{
var result = true;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
var command = connection.CreateCommand();
var transaction = connection.BeginTransaction();
command.Connection = connection;
command.Transaction = transaction;
try
{
command.CommandText = "DELETE User WHERE UserID = " + userID.ToString();
command.ExecuteNonQuery();
transaction.Rollback();
}
catch
{
result = false;
}
}
return result;
}

Categories