我已經爲你寫了一個工作代碼。在生產系統中使用它之前,您可能需要進一步開發它,因爲它未經過測試並受SQL注入的限制。
@OrderBy:你也可以使用序號所允許的SQL(order by 1 ASC
將工作)
@columns:可以選擇使用序號或列名
進一步發展,可以添加其他變量表名,例如。
CREATE PROCEDURE dbo.Sample_Procedure
@Orderby nvarchar(100) = 'Name Asc',
@Columns nvarchar(100) = '1,2,3,Name'
AS
DECLARE @SQLString nvarchar(500)
DECLARE @UsedColumns nvarchar(500)
DECLARE @X xml
/*
Using string manipulation and covert to transform @Columns to xml,
so 1,2,3 becomes: <root><s>1</s><s>2</s><s>2</s></root> and then
converted to XML so we can select from it as if it was a table.
if you have SQL 2016 it's possible to replace it with STRING_SPLIT
*/
SELECT @X = CONVERT(xml,' <root> <s>' + REPLACE(@Columns,',','</s> <s>') + '</s> </root> ')
DECLARE @ColsTab as TABLE (Col nvarchar(100))
/*This part "shreds" the xml above into the variable table @ColsTab.
we need it for the `IN' operator later.
*/
INSERT into @ColsTab (col)
SELECT T.c.value('.','varchar(20)') FROM @X.nodes('/root/s') T(c)
SET @UsedColumns = STUFF( (SELECT ',' + COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME='tblStaging'
and (COLUMN_NAME in (Select Col from @ColsTab)
or ORDINAL_POSITION in (Select iif(IsNumeric(Col)=1,Col,Null) from @ColsTab)
)
FOR XML PATH('')),
1, 1, '')
SET @SQLString = 'Select '+ @UsedColumns +'
from tblStaging
order by '[email protected]by+'
FOR XML RAW (''TRAN''), ROOT (''SEPA''), ELEMENTS';
EXECUTE sp_executesql @SQLString
RETURN
相同的查詢,這一次的動態查詢也設置輸出列的順序:
CREATE PROCEDURE dbo.Sample_Procedure2
@Orderby nvarchar(100) = 'Name Asc',
@Columns nvarchar(100) = '2,3,Name'
AS
DECLARE @SQLString nvarchar(500)
DECLARE @UsedColumns nvarchar(500)
DECLARE @X xml
/*
Using string manipulation and covert to transform @Columns to xml,
so 1,2,3 becomes: <root><s>1</s><s>2</s><s>2</s></root> and then
converted to XML so we can select from it as if it was a table.
if you have SQL 2016 it's possible to replace it with STRING_SPLIT
*/
SELECT @X = CONVERT(xml,' <root> <s>' + REPLACE(@Columns,',','</s> <s>') + '</s> </root> ')
DECLARE @ColsTab as TABLE (Col nvarchar(100))
/*This part "shreds" the xml above into the variable table @ColsTab.
we need it for the `IN' operator later.
*/
INSERT into @ColsTab (col)
SELECT T.c.value('.','varchar(20)') FROM @X.nodes('/root/s') T(c)
/* This version usues left join to assume the same order of
columns as specified in the input field @Columns
be mindful not to specify the same field twice
*/
SET @UsedColumns = STUFF( (
SELECT ',' + i.COLUMN_NAME
FROM @ColsTab as c
LEFT JOIN INFORMATION_SCHEMA.COLUMNS as i
ON i.COLUMN_NAME = Col
OR ORDINAL_POSITION = iif(IsNumeric(Col)=1,Col,Null)
WHERE TABLE_NAME='tblStaging'
AND COLUMN_NAME is not null
FOR XML PATH('')),
1, 1, '')
SET @SQLString = 'Select '+ @UsedColumns +'
from tblStaging
order by '[email protected]+'
FOR XML RAW (''TRAN''), ROOT (''SEPA''), ELEMENTS';
EXECUTE sp_executesql @SQLString
RETURN
需要更多信息。數據的目的是什麼?你需要所有的結果還是一些?有沒有理由不能在框架級別處理訂單? –