我很确定答案是'不',但只是想仔细检查。我有一个网站,允许用户选择他们想要在报告中看到哪些列。这些列存储在sql表中:
CREATE TABLE [dbo].[colNames]
(
[colID] [int] IDENTITY(1,1) NOT NULL,
[colName] [varchar](100) NULL,
CONSTRAINT [PK_colNames]
PRIMARY KEY CLUSTERED ([colID] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY]
) ON [PRIMARY]
GO
INSERT INTO [dbo].[colNames]
Select 'schoolNo'
UNION
Select 'locationName'
UNION
Select 'locationAlias'
UNION
Select 'schoolLevel'
UNION
Select 'schoolArea'
Union
Select 'stateClassification'
用户通过下拉框选择字段,并将ID作为字符串参数返回到SQL Server存储过程,因此如果他们选择locationAlias,schoolArea和stateClassification,则字符串将如下所示:'2,4 ,5'
要查询的表:
CREATE TABLE [dbo].[location]
(
[schoolID] [int] NOT NULL,
[schoolNo] [varchar](7) NULL,
[locationName] [varchar](50) NULL,
[locationAlias] [varchar](50) NULL,
[schoolLevel] [varchar](5) NULL,
[schoolLevelAbbrev] [varchar](5) NULL,
[schoolLevelDescription] [varchar](25) NULL,
[schoolArea] [varchar](25) NULL,
[stateClassification] [varchar](10) NULL,
CONSTRAINT [PK_location]
PRIMARY KEY CLUSTERED ([schoolID] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
Insert Into location
Select '001','Doss High','Doss','03','H','High','2','A1'
Union
Select '002','Stuart Middle','Stuart','02','M','Middle','3','A1'
Union
Select '003','Trunnel Elementary','Trunnel','01','E','Elementary','5','A1'
所以动态查询看起来像:
Select locationAlias, schoolArea, stateClassification
From location
这是我必须构建的查询的一个非常简化的版本,其中大多数都是冗长而复杂的。我知道如何通过创建变量并将查询写入变量并调用sp_executeSQL来构建动态查询,但它们很难修改和调试。我希望通过SQL Server 2012,有一种更简单的方法来构建动态列的查询,也许我不知道?有什么建议吗?
答案 0 :(得分:1)
有很多方法可以做你想要的但是它会比写出动态的sql更复杂。
我在互联网上找到了一个非常好用的免费工具。 Static SQL Converter
这将为你提供一个很好的骨架。你将不得不带走一些额外的单引号和管道'||'除此之外,效果非常好。
我发现帮助的另一种方法是运行
PRINT @SQL
然后你可以看到你正在运行的确切的SQL,你可以搞乱引号,直到你正确而不必猜测它。