SQL Query在管理工作室中工作,但在C#中不起作用

时间:2011-03-21 09:12:07

标签: c# asp.net ssms

使用我的软件进行查询时遇到问题......

我有一个构建我的查询的函数,然后执行它来填充gridview。但它不断给我一个例外:“多部分标识符”“不能与几列绑定”。

当我在SQL Management Studio中尝试查询时,它运行正常。我真的不明白。这是查询。

SELECT DISTINCT [NonConformite].[Numero],
CAST ([NonConformite].[Numero] AS varchar (255)) AS Champ1, 
CAST ([NonConformiteDonneesComplementaires177_4].[Texte2] AS varchar (255)) AS Champ2, 
CAST (NonConformite.dbo.[NonConformiteStatut].[Libelle] AS varchar (255)) AS Champ3, 
CAST ([NonConformite].[Description] AS varchar (255)) AS Champ4 FROM [NonConformite].[dbo].[NonConformite]  
LEFT JOIN NonConformite.dbo.[NonConformiteDonneesComplementaires] as NonConformiteDonneesComplementaires177_4 
ON [NonConformite].[Numero] = [NonConformiteDonneesComplementaires177_4].[Numero] 
LEFT JOIN NonConformite.dbo.[NonConformiteStatut] 
ON [NonConformite].[CpteurStatut] = NonConformite.dbo.[NonConformiteStatut].[Cpteur]

我在Windows 7 Pro上工作,使用Visual Studio 2008,SQL Server 2008和ASP.NET C#。

感谢您的回答!

2 个答案:

答案 0 :(得分:2)

我首先将查询分解为别名 - 看看是否有帮助;除非你故意做跨数据库工作(通常是个坏主意),否则删除数据库标识符并使​​用当前的数据库:

SELECT DISTINCT nc.[Numero],
CAST (nc.[Numero] AS varchar (255)) AS Champ1, 
CAST (dc.[Texte2] AS varchar (255)) AS Champ2, 
CAST (st.[Libelle] AS varchar (255)) AS Champ3, 
CAST (nc.[Description] AS varchar (255)) AS Champ4
FROM dbo.[NonConformite] nc
LEFT JOIN dbo.[NonConformiteDonneesComplementaires] dc
ON nc.[Numero] = dc.[Numero] 
LEFT JOIN dbo.[NonConformiteStatut] st
ON nc.[CpteurStatut] = st.[Cpteur]

答案 1 :(得分:1)

尝试运行以下操作,并从底部向上删除注释,直到您可以确定问题所在。

SELECT *
--DISTINCT [NonConformite].[Numero],
--CAST ([NonConformite].[Numero] AS varchar (255)) AS Champ1, 
--CAST ([NonConformiteDonneesComplementaires177_4].[Texte2] AS varchar (255)) AS Champ2, 
--CAST (NonConformite.dbo.[NonConformiteStatut].[Libelle] AS varchar (255)) AS Champ3, 
--CAST ([NonConformite].[Description] AS varchar (255)) AS Champ4
FROM [NonConformite].[dbo].[NonConformite]  
-- LEFT JOIN NonConformite.dbo.[NonConformiteDonneesComplementaires] as NonConformiteDonneesComplementaires177_4 
    ON [NonConformite].[Numero] = [NonConformiteDonneesComplementaires177_4].[Numero] 
-- LEFT JOIN NonConformite.dbo.[NonConformiteStatut] 
    ON [NonConformite].[CpteurStatut] = NonConformite.dbo.[NonConformiteStatut].[Cpteur]