private void Data_SS()
{
try
{
StringBuilder stringBuilder = new StringBuilder();
string text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
string text2 = "SELECT DeviceInfo.UniqueID,DeviceInfo.DevLabel,DeviceInfo.UWring,DeviceInfo.SZero,DeviceInfo.DWring,DeviceInfo.UAlarm,DeviceType.TypeName, Address.AddrName, RealData.Value, RealData.VStatus,";
text2 += "RealData.VTime,DeviceStatus.StatName, (CASE WHEN (deviceinfo.VZero = (CAST(realdata.Value AS INT) & 65535)) ";
text2 += "THEN 1 WHEN (deviceinfo.VOne = (CAST(realdata.Value AS INT) & 65535)) THEN 2 ELSE 0 END) AS SwitchValue, DeviceInfo.TypeID,";
text2 += "RealData.BATime,RealData.AMaxValue,RealData.AMaxTime,RealData.AMinValue,RealData.AMinTime,RealData.AAvgValue,";
text2 += "RealData.BCTime,RealData.CMaxValue,RealData.CMaxTime,RealData.CMinValue,RealData.CMinTime,RealData.CAvgValue FROM RealData ";
text2 += "LEFT OUTER JOIN DeviceInfo ON RealData.UniqueID = DeviceInfo.UniqueID ";
text2 += "LEFT OUTER JOIN DeviceType ON DeviceInfo.TypeID = DeviceType.TypeID ";
text2 += "LEFT OUTER JOIN DeviceStatus ON RealData.VStatus & 65535 = DeviceStatus.StatID ";
text2 += "LEFT OUTER JOIN Address ON DeviceInfo.AddrID = Address.AddrID ";
text2 += " LEFT OUTER JOIN NetPointType as d ON RealData.UniqueID = d.UniqueID ";
text2 += "WHERE (DeviceInfo.TypeID > 100000 AND DeviceInfo.TypeID < 508999 OR DeviceInfo.TypeID=2120002 OR DeviceInfo.TypeID=2120005) ";
text2 = text2 + "AND (DeviceInfo.DeleteTime IS NULL) AND " + this.TJFlag + " ";
text2 += "order by DeviceInfo.DevLabel";
int num = 0;
stringBuilder.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
stringBuilder.Append("<root code=\"DB14/T 671.1-2012\">");
stringBuilder.Append(string.Concat(new string[]
{
"<head cs_mine_code=\"",
this.ObjectConfig.MineNumber,
"\" cs_data_time=\"",
text,
"\" />"
}));
DataTable dataTable = this.ExeSql.ExecuteTable(text2);
if (dataTable != null)
{
foreach (DataRow dataRow in dataTable.Rows)
{
string[] array = new string[4];
string text3 = dataRow["DevLabel"].ToString().Trim();
string[] array2 = text3.Split(new char[]
{
'-'
});
if (array2.Length >= 2)
{
text3 = array2[1].Trim();
if (!text3.Contains("Q"))
{
string s = dataRow["VStatus"].ToString().Trim();
int num2 = int.Parse(s);
string text4 = dataRow["BATime"].ToString().Trim();
string text5 = dataRow["SwitchValue"].ToString().Trim();
string text6 = dataRow["StatName"].ToString().Trim();
string text7 = dataRow["UWring"].ToString().Trim();
string UWring = dataRow["UWring"].ToString().Trim();
string DWring= dataRow["DWring"].ToString().Trim();
string SZero= dataRow["SZero"].ToString().Trim();
string UniqueID = dataRow["UniqueID"].ToString().Trim();
if (text7.Length == 0)
{
text7 = dataRow["UAlarm"].ToString().Trim();
}
string text8 = dataRow["TypeID"].ToString().Trim();
if (!text8.Equals("201010"))
{
string text9 = dataRow["TypeName"].ToString().Trim();
string text10 = this.ChangeTypeId(text8, text9, dataRow["AddrName"].ToString().Trim());
string text11 = text3 + text10;
if (text3.EndsWith("F00"))
{
text11 = text3;
}
string str = text3.Substring(0, 3);
if (text3.StartsWith("D0"))
{
str = text3.Substring(1, 3);
}
array[0] = "<data ss_station_code=\"000" + str + "\"";
array[1] = "ss_transducer_code=\"" + text3 + "\"";
if (text10.Length != 0)
{
if (!this.FindCode(text11))
{
this.ConClass.WriteLogFiles("Error", "无: " + text11);
}
else
{
string str2 = base.MathRound(dataRow["Value"].ToString().Trim(), 2);
int num3 = int.Parse(text8);
string str3 = "0";
string text12 = text3.Substring(3, 1);
if (num3 > 900000 && num3 < 999999)
{
if (text5.Equals("0"))
{
str3 = "1";
str2 = "1";
}
else
{
str3 = "0";
if (text5.Equals("1"))
{
str2 = "1";
}
else
{
str2 = "0";
}
}
array[3] = "ss_switching_value=\"" + str2 + "\" />";
}
else if ((num3 > 200000 && num3 < 400000) || num3 == 2120002 || num3 == 2120005)
{
if ((num2 & 65535) == 24)
{
str2 = "0";
if ((num2 & 65536) == 65536)
{
str3 = "13";
}
else
{
str3 = "8";
guzhang = true;
}
}
else if ((num2 & 65535) != 20 && text5.Equals("0"))
{
if (text10.Equals("K0005"))
{
if (text6.Contains("副") || text6.Contains("主"))
{
str2 = "0";
}
else
{
if ((num2 & 65536) == 65536)
{
str3 = "13";
}
else
{
str3 = "5";
guzhang = true;
}
str2 = "0";
}
}
else
{
if ((num2 & 65536) == 65536)
{
str3 = "13";
}
else
{
str3 = "5";
guzhang = true;
}
str2 = "0";
}
}
else if (text10.Equals("K0007"))
{
if (text6.Contains("有"))
{
if ((num2 & 131072) == 131072)
{
str3 = "4";
moni = false;
}
else if ((num2 & 65536) == 65536)
{
str3 = "13";
}
else
{
str3 = "1";
}
str2 = "1";
}
else
{
str2 = "0";
}
}
else if (text10.Equals("K0005"))
{
if (text6.Contains("开"))
{
if ((num2 & 65536) == 65536)
{
str3 = "13";
}
else
{
str3 = "1";
}
str2 = "1";
}
else
{
str2 = "0";
}
}
else if (text5.Equals("1"))
{
if (num3 == 2120002 || num3 == 2120005)
{
if ((num2 & 65536) == 65536)
{
str3 = "9";
}
else
{
str3 = "1";
}
}
else if (text9.Contains("馈电") || text9.Contains("风筒") || text9.Contains("控制量"))
{
if ((num2 & 65536) == 65536)
{
str3 = "11";
}
else if (text9.Contains("风筒"))
{
str3 = "1";
}
}
str2 = "0";
}
else
{
str2 = "1";
}
array[3] = "ss_switching_value=\"" + str2 + "\" />";
}
else
{
if ((num2 & 65535) == 24)
{
if ((num2 & 65536) == 65536)
{
str3 = "13";
}
else
{
str3 = "8";
}
str2 = "-9999";
}
else if ((num2 & 65535) == 23)
{
if ((num2 & 65536) == 65536)
{
str3 = "13";
}
else
{
str3 = "5";
guzhang = true;
}
str2 = "-9999";
}
else if ((num2 & 131072) == 131072)
{
str3 = "4";
moni = false;
}
else if ((num2 & 524288) == 524288)
{
if ((num2 & 65536) == 65536)
{
str3 = "10";
}
else
{
str3 = "2";
}
}
else if ((num2 & 2097414) == 2097414)
{
str3 = "0";
moni = true;
}
else if ((num2 & 262406) == 262406 || (num2 & 262401) == 262401)
{
if ((num2 & 65536) == 65536)
{
str3 = "10";
}
else
{
str3 = "1";
moni = true;
}
}
else
{
str3 = "0";
}
array[3] = "ss_analog_value=\"" + str2 + "\" />";
}
array[2] = "ss_transducer_state=\"" + str3 + "\"";
string value = base.ArrayToStr(" ", "", array);
stringBuilder.Append(value);
num++;
}
}
}
}
}
}
stringBuilder.Append("</root>");
if (num > 0)
{
string text13 = this.ObjectConfig.MineNumber + "AQSS" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xml";
File.WriteAllText(this.ObjectConfig.OutFilePath + "\\" + text13, stringBuilder.ToString(), Encoding.UTF8);
this.ConClass.WriteLogFiles("File", string.Concat(new string[]
{
"任务: ",
this.ObjectConfig.TaskName,
" 生成 ",
text13,
" 文件成功"
}));
if (Config.BackFiles)
{
string str4 = text13;
string str5 = string.Concat(new string[]
{
Application.StartupPath,
"\\BackFiles\\",
DateTime.Now.ToString("yyyyMMdd"),
"\\",
this.ObjectConfig.TaskName
});
File.WriteAllText(str5 + "\\" + str4, stringBuilder.ToString(), Encoding.UTF8);
}
}
}
}
catch (Exception ex)
{
this.ConClass.WriteLogFiles("Error", "Data_SS: " + ex.Message);
}
}
现在是获取第一个数据库内容,生成文件,想实现获取第二个数据库内容和第一个库同时生成,这种怎么实现呢。
```c#
```
使用第一个库相同的方式,把数据从第二个数据库读取出来,然后将数据库一和数据库二分别得到的数据进行合并即可。
示例代码如下:
using Dapper;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
namespace ConsoleApp1
{
public class Program
{
private const string ConnectionString1 = "Server=(localdb)\\mssqllocaldb;Integrated Security=true;Database=Demo";
private const string ConnectionString2 = "Server=(localdb)\\mssqllocaldb;Integrated Security=true;Database=Demo2";
static void Main(string[] args)
{
// 从数据库一获取字段为Name的数据
var list1 = GetName(ConnectionString1);
// 从数据库二获取字段为Name的数据
var list2 = GetName(ConnectionString2);
// 将两个数据的数据进行合并
var result = list1
.Concat(list2)
.ToList();
// 在控制台打印合并后的结果
Console.WriteLine(string.Join(Environment.NewLine, result));
// 将内容保存到文件
File.WriteAllLines(@"D:\demo.txt", result);
Console.ReadKey();
}
static List<string> GetName(string connectionString)
{
using SqlConnection connection = new SqlConnection(connectionString);
var demo1 = connection.Query<string>("SELECT Name FROM Customer").ToList();
return demo1;
}
}
}
示例数据库一和数据库二的数据分别为:
运行结果:
输出的文件结果:
你只需要将两个不同IP的数据库连接改成你对应的即可。
难点在哪里呢?看不出问题在什么地方。
没太明白你的意思。
你需要在你操作第一张表时加一个触发器,你得从SQL语句那块下手,类似于这样
UPDATE prediksi_alokas pa
SET total_pengeluaran = (SELECT SUM(add.jumlah_alokasi)
FROM alokasi_dana_desa add
WHERE add.jenis_transaksi = 'Alokasi Keluar' AND
EXTRACT(YEAR_MONTH FROM add.tanggal_alokasi) = EXTRACT(YEAR_MONTH FROM new.tanggal_alokasi)
)
WHERE pa.bulan = MONTH(new.tanggal_alokasi);
SQL触发器:
触发器是一种特殊类型的存储过程,它不同于之前的我们介绍的存储过程。触发器主要是通过事件进行触发被自动调用执行的。而存储过程可以通过存储过程的名称被调用。
触发器对表进行插入、更新、删除的时候会自动执行的特殊存储过程。触发器一般用在check约束更加复杂的约束上面。触发器和普通的存储过程的区别是:触发器是当对某一个表进行操作。诸如:update、insert、delete这些操作的时候,系统会自动调用执行该表上对应的触发器。SQL Server 2005中触发器可以分为两类:DML触发器和DDL触发器,其中DDL触发器它们会影响多种数据定义语言语句而激发,这些语句有create、alter、drop语句。
DML触发器分为:
1、 after触发器(之后触发)
a、 insert触发器
b、 update触发器
c、 delete触发器
2、 instead of 触发器 (之前触发)
其中after触发器要求只有执行某一操作insert、update、delete之后触发器才被触发,且只能定义在表上。而instead of触发器表示并不执行其定义的操作(insert、update、delete)而仅是执行触发器本身。既可以在表上定义instead of触发器,也可以在视图上定义。
触发器有两个特殊的表:插入表(instered表)和删除表(deleted表)。这两张是逻辑表也是虚表。有系统在内存中创建者两张表,不会存储在数据库中。而且两张表的都是只读的,只能读取数据而不能修改数据。这两张表的结果总是与被改触发器应用的表的结构相同。当触发器完成工作后,这两张表就会被删除。Inserted表的数据是插入或是修改后的数据,而deleted表的数据是更新前的或是删除的数据。
对表的操作
Inserted逻辑表
Deleted逻辑表
增加记录(insert)
存放增加的记录
无
删除记录(delete)
无
存放被删除的记录
修改记录(update)
存放更新后的记录
存放更新前的记录
Update数据的时候就是先删除表记录,然后增加一条记录。这样在inserted和deleted表就都有update后的数据记录了。注意的是:触发器本身就是一个事务,所以在触发器里面可以对修改数据进行一些特殊的检查。如果不满足可以利用事务回滚,撤销操作。
Ø 创建触发器
语法
create trigger tgr_name
on table_name
with encrypion –加密触发器
for update...
as
Transact-SQL
# 创建insert类型触发器
--创建insert插入类型触发器
if (object_id('tgr_classes_insert', 'tr') is not null)
drop trigger tgr_classes_insert
go
create trigger tgr_classes_insert
on classes
for insert --插入触发
as
--定义变量
declare @id int, @name varchar(20), @temp int;
--在inserted表中查询已经插入记录信息
select @id = id, @name = name from inserted;
set @name = @name + convert(varchar, @id);
set @temp = @id / 2;
insert into student values(@name, 18 + @id, @temp, @id);
print '添加学生成功!';
go
--插入数据
insert into classes values('5班', getDate());
--查询数据
select * from classes;
select * from student order by id;
insert触发器,会在inserted表中添加一条刚插入的记录。
# 创建delete类型触发器
--delete删除类型触发器
if (object_id('tgr_classes_delete', 'TR') is not null)
drop trigger tgr_classes_delete
go
create trigger tgr_classes_delete
on classes
for delete --删除触发
as
print '备份数据中……';
if (object_id('classesBackup', 'U') is not null)
--存在classesBackup,直接插入数据
insert into classesBackup select name, createDate from deleted;
else
--不存在classesBackup创建再插入
select * into classesBackup from deleted;
print '备份数据成功!';
go
--
--不显示影响行数
--set nocount on;
delete classes where name = '5班';
--查询数据
select * from classes;
select * from classesBackup;
delete触发器会在删除数据的时候,将刚才删除的数据保存在deleted表中。
# 创建update类型触发器
--update更新类型触发器
if (object_id('tgr_classes_update', 'TR') is not null)
drop trigger tgr_classes_update
go
create trigger tgr_classes_update
on classes
for update
as
declare @oldName varchar(20), @newName varchar(20);
--更新前的数据
select @oldName = name from deleted;
if (exists (select * from student where name like '%'+ @oldName + '%'))
begin
--更新后的数据
select @newName = name from inserted;
update student set name = replace(name, @oldName, @newName) where name like '%'+ @oldName + '%';
print '级联修改数据成功!';
end
else
print '无需修改student表!';
go
--查询数据
select * from student order by id;
select * from classes;
update classes set name = '五班' where name = '5班';
update触发器会在更新数据后,将更新前的数据保存在deleted表中,更新后的数据保存在inserted表中。
# update更新列级触发器
if (object_id('tgr_classes_update_column', 'TR') is not null)
drop trigger tgr_classes_update_column
go
create trigger tgr_classes_update_column
on classes
for update
as
--列级触发器:是否更新了班级创建时间
if (update(createDate))
begin
raisError('系统提示:班级创建时间不能修改!', 16, 11);
rollback tran;
end
go
--测试
select * from student order by id;
select * from classes;
update classes set createDate = getDate() where id = 3;
update classes set name = '四班' where id = 7;
更新列级触发器可以用update是否判断更新列记录;
# instead of类型触发器
instead of触发器表示并不执行其定义的操作(insert、update、delete)而仅是执行触发器本身的内容。
创建语法
create trigger tgr_name
on table_name
with encryption
instead of update...
as
T-SQL
# 创建instead of触发器
if (object_id('tgr_classes_inteadOf', 'TR') is not null)
drop trigger tgr_classes_inteadOf
go
create trigger tgr_classes_inteadOf
on classes
instead of delete/, update, insert/
as
declare @id int, @name varchar(20);
--查询被删除的信息,病赋值
select @id = id, @name = name from deleted;
print 'id: ' + convert(varchar, @id) + ', name: ' + @name;
--先删除student的信息
delete student where cid = @id;
--再删除classes的信息
delete classes where id = @id;
print '删除[ id: ' + convert(varchar, @id) + ', name: ' + @name + ' ] 的信息成功!';
go
--test
select * from student order by id;
select * from classes;
delete classes where id = 7;
# 显示自定义消息raiserror
if (object_id('tgr_message', 'TR') is not null)
drop trigger tgr_message
go
create trigger tgr_message
on student
after insert, update
as raisError('tgr_message触发器被触发', 16, 10);
go
--test
insert into student values('lily', 22, 1, 7);
update student set sex = 0 where name = 'lucy';
select * from student order by id;
# 修改触发器
alter trigger tgr_message
on student
after delete
as raisError('tgr_message触发器被触发', 16, 10);
go
--test
delete from student where name = 'lucy';
# 启用、禁用触发器
--禁用触发器
disable trigger tgr_message on student;
--启用触发器
enable trigger tgr_message on student;
# 查询创建的触发器信息
--查询已存在的触发器
select * from sys.triggers;
select * from sys.objects where type = 'TR';
--查看触发器触发事件
select te.* from sys.trigger_events te join sys.triggers t
on t.object_id = te.object_id
where t.parent_class = 0 and t.name = 'tgr_valid_data';
--查看创建触发器语句
exec sp_helptext 'tgr_message';
# 示例,验证插入数据
if ((object_id('tgr_valid_data', 'TR') is not null))
drop trigger tgr_valid_data
go
create trigger tgr_valid_data
on student
after insert
as
declare @age int,
@name varchar(20);
select @name = s.name, @age = s.age from inserted s;
if (@age < 18)
begin
raisError('插入新数据的age有问题', 16, 1);
rollback tran;
end
go
--test
insert into student values('forest', 2, 0, 7);
insert into student values('forest', 22, 0, 7);
select * from student order by id;
# 示例,操作日志
if (object_id('log', 'U') is not null)
drop table log
go
create table log(
id int identity(1, 1) primary key,
action varchar(20),
createDate datetime default getDate()
)
go
if (exists (select * from sys.objects where name = 'tgr_student_log'))
drop trigger tgr_student_log
go
create trigger tgr_student_log
on student
after insert, update, delete
as
if ((exists (select 1 from inserted)) and (exists (select 1 from deleted)))
begin
insert into log(action) values('updated');
end
else if (exists (select 1 from inserted) and not exists (select 1 from deleted))
begin
insert into log(action) values('inserted');
end
else if (not exists (select 1 from inserted) and exists (select 1 from deleted))
begin
insert into log(action) values('deleted');
end
go
--test
insert into student values('king', 22, 1, 7);
update student set sex = 0 where name = 'king';
delete student where name = 'king';
select * from log;
select * from student order by id;