2010-12-02 70 views
2

我有一个从sql server(2005)获取数据的c#应用程序(2008)。 我在SQL Server中的观点,即显示准备数据,像这样(简化):在视图后面获取sql语句

select Places.Name as [Location], Parts.Name as [Part Name] 
from Places inner join Parts 
on Places.Id=Parts.Location 

我有中内置的代码,犹如“其中”语句来过滤这一点:

where (Places.Id=1 or Places.Id=15) and 
     (Parts.Id=56 or Parts.Id=8 or Parts.Id=32) 

当然我能保持基本的select语句在我的代码,但我likw只在一个地方已经确定的事情:),问题是,如果有什么办法让SQL Server中的观点背后的select语句?或者获取存储过程的内容? 非常感谢!

回答

1

看看Information Schema View,你会发现你的解决方案。

+0

谢谢!这正是我想要的!我将准备一个存储过程,它将带上字符串并从中删除“create view .... as”。 – Leon 2010-12-02 07:25:34

+0

不客气pal – 2010-12-02 07:31:52

+0

+1。我一直在忘记信息模式......我一定会变老。 – 2010-12-02 07:43:35

0

使用信息架构视图作为贾尼认为是一种选择。

另一个是使用存储过程sp_helptext的系统。 sp_helptext YourViewsp_helptext YourStoredProcedure可以获取整个对象定义。

您可以找到有关在sp_helptext系统存储过程here更多信息。

using (SqlConnection connection = new SqlConnection(connectionString)) 
{ 
    connection.Open(); 

    string selectCommand = "EXEC sp_YourStoredProcedure @whereClause"; 

    SqlCommand command = new SqlCommand(selectCommand, connection); 
    command.Parameters.Add("@whereClause", System.Data.SqlDbType.NVarChar); 
    command.Parameters["@whereClause"] = whereClause; 
    using (SqlDataReader reader = command.ExecuteReader()) 
    { 
     while (reader.NextResult()) 
     { 
      string location = reader.GetString(0); 
      string partName = reader.GetString(1); 

      // do something 
     } 
    } 

    connection.Close(); 
} 

编辑:

0

如果你想有一个存储过程执行查询(并结合你的基本的查询字符串,用你的where子句),可以使用下面的代码实现这一点动态存储过程:

CREATE PROCEDURE sp_YourStoredProcedure 
(
    @whereClause NVARCHAR(MAX) 
) 
AS 
BEGIN 
    DECLARE @sql AS NVARCHAR(MAX) 

    SET @sql = N' 
    select Places.Name as [Location], Parts.Name as [Part Name] 
    from Places inner join Parts 
    on Places.Id=Parts.Location ' 
    + @whereClause 

    EXEC sp_executesql @sql 
END