假设您有一个像这样的存储过程,它选择 0(表不存在)或 1(表确实存在)
CREATE PROCEDURE dbo.DoesTableExist (@TableName NVARCHAR(100))
AS
BEGIN
IF EXISTS (SELECT * FROM sys.tables WHERE Name = @TableName)
SELECT 1
ELSE
SELECT 0
END
那么您可以编写此 C# 代码来获取值 - 使用.ExecuteScalar()
因为您只期望单行单列:
// set up connection and command
using (SqlConnection conn = new SqlConnection("your-connection-string-here"))
using (SqlCommand cmd = new SqlCommand("dbo.DoesTableExist", conn))
{
// define command to be stored procedure
cmd.CommandType = CommandType.StoredProcedure;
// add parameter
cmd.Parameters.Add("@TableName", SqlDbType.NVarChar, 100).Value = "your-table-name-here";
// open connection, execute command, close connection
conn.Open();
int result = (int)cmd.ExecuteScalar();
conn.Close();
}
如果表不存在,现在result
将包含 a - 或,如果它确实存在。0
1