我有一个sourcetable,我想使用动态SQL从中创建不同的表。
sourceTable会:
ACCP_AcceptantID TransactionID Descrption Period AcceptantNumber
1 12 A 201801 16
1 13 AA 201801 16
2 21 B 201801 22
2 46 BB 201801 22
3 31 C 201801 54
3 38 CC 201801 54
4 94 D 201801 62
4 96 DD 201801 62
为了能够使用WHILE循环来选择每个接受者,我创建了一个表接受者:
SELECT DISTINCT ACCP_AcceptantNr
INTO Acceptants
FROM Sourcetable
ALTER TABLE #TussentabelAcceptanten ADD ID INT IDENTITY
ACCP_AcceptantNr ID
16 1
22 2
54 3
62 4
所需结果(对于每个acceptantID,包含内容的自己的表):
ACCP_AcceptantID TransactionID Descrption Period AcceptantNumber
1 12 A 201801 16
1 13 AA 201801 16
我的查询尝试:
DECLARE @SQL NVARCHAR(MAX),
@Acceptant NVARCHAR(40),
@Row INT = 1
WHILE @Row <= ( SELECT MAX(ID) FROM Acceptants)
BEGIN
SELECT @Acceptant = ACCP_AcceptantNr FROM Acceptants
SET @SQL = 'SELECT *
INTO MyDatabase.dbo.'+ Period + @Acceptant'
FROM #SourceTable
WHERE ACCP_AcceptantNr = '+ @Acceptant''
EXEC (@SQL)
SET @Row = @Row + 1
SET @SQL = ''
END
错误消息:&#39;
附近的语法不正确动态SQL总是让我变得更好。我只是不知道在哪里放置引号。建议会很棒。感谢。
答案 0 :(得分:0)
您缺少+符号
SET @SQL = 'SELECT *
INTO MyDatabase.dbo.'+ Period + @Acceptant+'--Added +
FROM #SourceTable
WHERE ACCP_AcceptantNr = '+ @Acceptant -- Removed ''
由于你给Period
没有@符号,我认为它是某个表中的一列,所以从该表添加一个selet,否则会引发错误。
喜欢这个
SELECT @SQL = 'SELECT *
INTO MyDatabase.dbo.'+ Period + @Acceptant+'--Added +
FROM #SourceTable
WHERE ACCP_AcceptantNr = '+ @Acceptant -- Removed ''
FROM YourTableName