这是一个相当独特的问题,我不知道是否有答案。我试图输入可变数量的记录,以根据另一个表的值插入表中。这就是我试过的
insert into TABLE1
select TOP cast((select Value from TABLE3 WHERE column_name = 'blah') as int) * from TABLE2
所以我试图从表3中获取值,并使用该值从表2中获取前x个记录以插入表1中。
列出的错误是附近强制转换的语法错误。
答案 0 :(得分:3)
TOP x不能在变量中指定。实际上可以看到KM的答案(肯定比我的好)。
此处的选项是动态查询
DECLARE @topx AS integer;
SET @topx = (select Value from TABLE3 WHERE column_name = 'blah')
DECLARE @query AS varchar(max);
SET @query = 'INSERT INTO table1 SELECT TOP ' + convert(varchar(10),@topx)
+ ' FROM table2'
exec sp_executesql query
答案 1 :(得分:2)
declare @YourTable table (RowID int identity(1,1), ColA char(4))
INSERT INTO @YourTable values ('a');INSERT INTO @YourTable values ('aa');INSERT INTO @YourTable values ('aaa');
INSERT INTO @YourTable values ('b');INSERT INTO @YourTable values ('bb');INSERT INTO @YourTable values ('bbb');
INSERT INTO @YourTable values ('c');INSERT INTO @YourTable values ('cc');INSERT INTO @YourTable values ('ccc');
declare @x int=5
select top (@x) * from @YourTable
输出:
RowID ColA
----------- ----
1 a
2 aa
3 aaa
4 b
5 bb
(5 row(s) affected)
答案 2 :(得分:0)
您可以在行号上使用where子句来执行相同的操作。像
这样的东西insert into TABLE1
select * from TABLE2 where row_number < cast((select Value from TABLE3 WHERE column_name = 'blah') as int)
代码尚未经过测试,只是显示了这个想法。
答案 3 :(得分:0)
有一种方法可以在SELECT TOP(N)
中将N的值作为列名传递,而无需使用任何变量或动态sql。
见下文:
<强> TESTDATA 强>
DECLARE @TABLE3 TABLE (VALUE INT)
INSERT INTO @TABLE3 VALUES
(1),(2),(3),(4),(5),(6)
DECLARE @TABLE2 TABLE (VALUE INT, OtherColumn INT)
INSERT INTO @TABLE2 VALUES
(1,1),(1,2),(1,3),(1,4),
(2,1),(2,2),(2,3),(2,4),
(3,1),(3,2),(3,3),(3,4)
<强>查询强>
SELECT T2.*
FROM @TABLE3 T3 CROSS APPLY
(SELECT TOP (T3.Value) *
FROM @TABLE2
WHERE VALUE = T3.VALUE) T2
结果集
╔═══════╦═════════════╗
║ VALUE ║ OtherColumn ║
╠═══════╬═════════════╣
║ 1 ║ 1 ║
║ 2 ║ 1 ║
║ 2 ║ 2 ║
║ 3 ║ 1 ║
║ 3 ║ 2 ║
║ 3 ║ 3 ║
╚═══════╩═════════════╝
查询您的数据
SELECT T2.*
FROM TABLE3 T3 CROSS APPLY
(SELECT TOP (T3.Value) *
FROM TABLE2
WHERE SomeColumn = T3.SomeColumn
AND ColumnName = 'blah') T2