T-SQL存储过程 - 只选择几列

时间:2015-09-30 16:12:28

标签: sql sql-server sql-server-2008 tsql

我有一个存储过程,它从表中选择所有列。但我只需选择其中几个。

如何指定变量以从表中选择几列?

现有存储过程代码:

DECLARE @DatabaseName NVARCHAR(255) = N’AdventureWorksDW’
DECLARE @SchemaName NVARCHAR(255) = N’dbo’
DECLARE @TableName NVARCHAR(255) = N’DimProduct’

BEGIN
SET NOCOUNT ON

-- Declare the parameters internal to query
DECLARE @SQLString NVARCHAR(MAX) = N”
DECLARE @ParamDefinition NVARCHAR(MAX) = N”
DECLARE @ColumnList TABLE (
ColumnId INT IDENTITY(1,1)
, ColumnName NVARCHAR(255)
, ColumnMaxLength INT
, ColumnMinLength INT
)

DECLARE @ColumnMaxLength INT
DECLARE @ColumnMinLength INT
DECLARE @ColumnCount INT = 0
DECLARE @LoopCounter INT = 1
DECLARE @ColumnName NVARCHAR(255)

SET @SQLString =
N’SELECT COLUMN_NAME FROM ‘
@DatabaseName + N’.’ + N’INFORMATION_SCHEMA.COLUMNS
WHERE
DATA_TYPE IN (”CHAR”, ”NCHAR”, ”VARCHAR”, ”NVARCHAR”)
AND TABLE_SCHEMA = @SchemaName
AND TABLE_NAME = @TableName’

SET @ParamDefinition = N’@SchemaName NVARCHAR(255), @TableName NVARCHAR(255)’

INSERT INTO @ColumnList (ColumnName)

EXECUTE sp_executesql @SQLString, @ParamDefinition, @SchemaName, @TableName
SELECT @ColumnCount = COUNT(*) FROM @ColumnList

WHILE (@LoopCounter <= @ColumnCount)

BEGIN

SELECT @ColumnName = ColumnName
FROM @ColumnList
WHERE ColumnId = @LoopCounter

SET @SQLString =
N’SELECT ‘
‘@ColumnMinLength = MIN(LEN(‘ + @ColumnName + ‘))’
‘, @ColumnMaxLength = MAX(LEN(‘ + @ColumnName + ‘))’
‘ FROM ‘
@DatabaseName + N’.’ + @SchemaName + N’.’ + @TableName
‘ WITH (NOLOCK) ‘

SET @ParamDefinition = N’@ColumnMinLength INT OUTPUT, @ColumnMaxLength INT OUTPUT’

EXECUTE sp_executesql @SQLString, @ParamDefinition, @ColumnMinLength OUTPUT, @ColumnMaxLength OUTPUT

UPDATE @ColumnList

SET
ColumnMinLength = @ColumnMinLength
, ColumnMaxLength = @ColumnMaxLength
WHERE ColumnId = @LoopCounter

SET @LoopCounter += 1

END

SELECT
ColumnName AS [Column Name]
, ColumnMinLength AS [Column Minimum Length]
, ColumnMaxLength AS [Column Maximum Length]
FROM @ColumnList
ORDER BY [Column Name]

END

2 个答案:

答案 0 :(得分:1)

您可以build dynamic SQL query按如下方式执行

create procedure SELECT_MyTable (
    @fieldList nvarchar(max)
)
as
declare @select nvarchar(max)

set @select = 'SELECT ' + @fieldList + ' FROM MyTable'

exec sp_executesql @select

GO

declare @fieldList nvarchar(max) = 'UserName,region'
exec SELECT_MyTable @fieldList

答案 1 :(得分:0)

您可以直接从表中选择而不是使用存储过程吗?

如果是这样,您可以使用语法

SELECT Column1, Column2, ColumnN
FROM MyTable