System.Data.SqlClient.SqlCommand 对象可以执行的 T-SQL 有哪些限制?
我有一些类似这样的 Transact-SQL,它可以通过 SqlCommand 对象执行吗?还是我需要开始学习 Sql 管理对象?
BEGIN TRANSACTION
BEGIN TRY
IF NOT EXISTS
(
SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_CATALOG = (SELECT DB_NAME())
AND TABLE_NAME = 'SchemaVersion'
)
BEGIN
Print 'Migrating up...'
CREATE TABLE SchemaVersion (
Id INT IDENTITY(1,1) NOT NULL,
Version INT NOT NULL,
CONSTRAINT PK_SchemaVersion PRIMARY KEY CLUSTERED (
Id ASC
)
)
INSERT INTO SchemaVersion (Version) VALUES(1)
PRINT 'Migrated from 0 to 1'
END
ELSE IF (SELECT Version FROM SchemaVersion) = 1
BEGIN
Print 'Migrating down...'
DROP TABLE Dia_SchemaVersion
PRINT 'Migrated from 1 to 0'
END
ELSE
PRINT 'Not migrating...'
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
END CATCH
I have some Transact-SQL that lloks like this, can it be executed through a SqlCommand object, or do I need to start learning Sql Management Objects?
BEGIN TRANSACTION
BEGIN TRY
IF NOT EXISTS
(
SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_CATALOG = (SELECT DB_NAME())
AND TABLE_NAME = 'SchemaVersion'
)
BEGIN
Print 'Migrating up...'
CREATE TABLE SchemaVersion (
Id INT IDENTITY(1,1) NOT NULL,
Version INT NOT NULL,
CONSTRAINT PK_SchemaVersion PRIMARY KEY CLUSTERED (
Id ASC
)
)
INSERT INTO SchemaVersion (Version) VALUES(1)
PRINT 'Migrated from 0 to 1'
END
ELSE IF (SELECT Version FROM SchemaVersion) = 1
BEGIN
Print 'Migrating down...'
DROP TABLE Dia_SchemaVersion
PRINT 'Migrated from 1 to 0'
END
ELSE
PRINT 'Not migrating...'
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
END CATCH
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,这可以通过 SqlCommand 执行 - 最简单的方法是将其放入存储过程中并执行它。
您有什么问题?
至于学习 SSMS——如果你在 SQL Server 上开发,那不是一个坏主意。
Yes, this can be executed by
SqlCommand
- the easiest way would be to put this in a stored procedure and execute that.What issues are you having?
As for learning SSMS - if you develop on SQL Server, that's not a bad idea.
只需将其包装在存储过程中并使用 SqlCommand 的 .ExecuteNonQuery() 方法调用它即可。您可以通过处理 SqlConnection 的 InfoMessage 事件。它还有助于将连接的 FireInfoMessageEventOnUserErrors 属性设置为 true。
Just wrap that in a Stored Procedure and call it using SqlCommand's .ExecuteNonQuery() method. You can "listen" to the print messages from your .Net code by handling the SqlConnection's InfoMessage event. It also helps to set the connection's FireInfoMessageEventOnUserErrors property to true.
您需要了解 ADO.NET 以及对象的工作原理,主要是
命令对象可以采用任何符合 SQL (ANSI SQL) 的查询。如果您要进行事务,那么我建议您
You need to understand ADO.NET and how the objects work, primarily
The Command object can take any SQL (ANSI SQL) compliant query. If you are going to have transactions, then I suggest you handle transactions