我希望用户浏览到不同的路径,在c:\script.sql
下更改我的SQL脚本@db
中的变量。
SQL脚本:
DECLARE @Table TABLE
(
BackupName NVARCHAR (128) ,
BackupDescription NVARCHAR (255) ,
BackupType SMALLINT ,
ExpirationDate DATETIME ,
Compressed BIT ,
Position SMALLINT ,
DeviceType TINYINT ,
UserName NVARCHAR (128) ,
ServerName NVARCHAR (128) ,
DatabaseName NVARCHAR (128) ,
DatabaseVersion INT ,
DatabaseCreationDate DATETIME ,
BackupSize NUMERIC (20, 0) ,
FirstLSN NUMERIC (25, 0) ,
LastLSN NUMERIC (25, 0) ,
CheckpointLSN NUMERIC (25, 0) ,
DatabaseBackupLSN NUMERIC (25, 0) ,
BackupStartDate DATETIME ,
BackupFinishDate DATETIME ,
SortOrder SMALLINT ,
CodePage SMALLINT ,
UnicodeLocaleId INT ,
UnicodeComparisonStyle INT ,
CompatibilityLevel TINYINT ,
SoftwareVendorId INT ,
SoftwareVersionMajor INT ,
SoftwareVersionMinor INT ,
SoftwareVersionBuild INT ,
MachineName NVARCHAR (128) ,
Flags INT ,
BindingID UNIQUEIDENTIFIER,
RecoveryForkID UNIQUEIDENTIFIER,
Collation NVARCHAR (128) ,
FamilyGUID UNIQUEIDENTIFIER,
HasBulkLoggedData BIT ,
IsSnapshot BIT ,
IsReadOnly BIT ,
IsSingleUser BIT ,
HasBackupChecksums BIT ,
IsDamaged BIT ,
BeginsLogChain BIT ,
HasIncompleteMetaData BIT ,
IsForceOffline BIT ,
IsCopyOnly BIT ,
FirstRecoveryForkID UNIQUEIDENTIFIER,
ForkPointLSN NUMERIC (25, 0) NULL,
RecoveryModel NVARCHAR (60) ,
DifferentialBaseLSN NUMERIC (25, 0) NULL,
DifferentialBaseGUID UNIQUEIDENTIFIER,
BackupTypeDescription NVARCHAR (60) ,
BackupSetGUID UNIQUEIDENTIFIER NULL,
CompressedBackupSize NUMERIC (20, 0)
);
INSERT INTO @table
EXECUTE ('RESTORE HEADERONLY FROM DISK = '@db'');
SELECT ServerName,
DatabaseName,
SoftwareVersionMajor,
SoftwareVersionMinor
FROM @table;
我想在C#中使用@DB =我的变量
C#代码:
public void PullData()
{
string connString = @"server=.\sqlserver2012; database = master; user =sam; pwd =sam; Connection Timeout = 15; MultipleActiveResultSets = true";
string script = File.ReadAllText(@"C:\Temp Table.sql");
string db = tb_bak_location.Text;
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(script, conn);
try
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(datatable);
dataGridView1.DataSource = datatable;
da.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
conn.Close();
}
}
我只是希望能够从该位置读取SQL脚本,然后在运行函数时实现我的db
变量。
希望这是有道理的
由于
答案 0 :(得分:1)
string db = tb_bak_location.Text;
string script = File.ReadAllText(@"C:\Temp Table.sql").Replace("@db", db);
答案 1 :(得分:0)
要通过您想要的某个外部值更改参数,您可以在代码隐藏中为参数赋值。 之后
SqlCommand cmd = new SqlCommand(script, conn);
使用
cmd.Parameters.AddWithValue(ParamName, Value);
还可以考虑在using块中创建SqlConnection和SqlCommand,以自动处理关闭和打开连接。
只是google:向sql脚本添加参数
示例链接:http://www.csharp-station.com/Tutorial/AdoDotNet/Lesson06