SQL Server:插入到新列';行不通
我错过了什么?我正试图用一个新列修改一个表,并将其插入。最后,我想插入一个变量SQL Server:插入到新列';行不通,sql,sql-server,tsql,insert,alter,Sql,Sql Server,Tsql,Insert,Alter,我错过了什么?我正试图用一个新列修改一个表,并将其插入。最后,我想插入一个变量@loopcounter。但它似乎不认识新专栏 这是桌子 SELECT [dbo].[webpages_UsersInRoles].[UserId], [dbo].[UserProfile].[UserName], [dbo].[UserProfile].[CustomerId], [dbo].[webpages_UsersInRoles].[RoleId], [dbo].[w
@loopcounter
。但它似乎不认识新专栏
这是桌子
SELECT
[dbo].[webpages_UsersInRoles].[UserId],
[dbo].[UserProfile].[UserName],
[dbo].[UserProfile].[CustomerId],
[dbo].[webpages_UsersInRoles].[RoleId],
[dbo].[webpages_Roles].[RoleName]
INTO
#ControlTable
FROM
[dbo].[webpages_UsersInRoles]
INNER JOIN
[dbo].[UserProfile] ON [dbo].[webpages_UsersInRoles].[UserId] = [dbo].[UserProfile].UserId
INNER JOIN
[dbo].[webpages_Roles] ON [webpages_UsersInRoles].[RoleId]=[dbo].[webpages_Roles].[RoleId]
WHERE
CustomerId = 'DEMO'
以及涂改/插入:
ALTER TABLE #ControlTable
ADD Loopfield INT;
INSERT INTO #ControlTable (Loopfield)
VALUES (1)
SELECT * FROM #ControlTable;
我想你想要:
alter table #ControlTable add LoopField int identity(1, 1);
或者只创建具有标识列的表:
SELECT identity(1, 1) as loopfield,
[dbo].[webpages_UsersInRoles].[UserId],
[dbo].[UserProfile].[UserName],
[dbo].[UserProfile].[CustomerId],
[dbo].[webpages_UsersInRoles].[RoleId],
[dbo].[webpages_Roles].[RoleName]
或者,如果您不打算在表中插入新行,row\u number()
就足够了:
SELECT row_number() over (order by (select null)) as loopfield,
[dbo].[webpages_UsersInRoles].[UserId],
[dbo].[UserProfile].[UserName],
[dbo].[UserProfile].[CustomerId],
[dbo].[webpages_UsersInRoles].[RoleId],
[dbo].[webpages_Roles].[RoleName]
对我来说很好
create table #temp (name varchar(10));
insert into #temp values ('bob'), ('mary');
ALTER TABLE #temp
ADD Loopfield INT;
declare @Loopfield int = 1;
INSERT INTO #temp (Loopfield)
VALUES (@Loopfield);
select * from #temp;
drop table #temp;
您得到的错误是什么?您是否在一个会话/事务中执行此操作?否则,您的临时表将无法在当前会话/事务之外被识别。在SQL Server中,循环通常是一个糟糕的设计选择。你在这里的最终目标是什么?(我有一种感觉,这可能是一个xy问题。)最终,我想循环表中的每个项目,在我插入角色表中的用户时使用此表,以将具有相同dealerid的某些用户添加到新角色。为什么需要循环来完成此操作?使用数据集方法似乎更好,因为它无法识别插入中的列。我在同一个事务中运行这个。当我试图运行这段代码的时候,我得到了我试图运行这段代码的时候,我得到了“不能插入值的NULL”不能插入值的值,我得到的“不能插入值的NULL”不能插入值,我得到的“不能插入值的值”当我试图运行这段代码的时候,我得到“不能插入值”不能插入值的值,我得到“不能插入值的值”不能插入列“用户ID”用户ID,表'temdb.dbo.dbo。我的控制表,控制表,控制表,控制表,UUUUUuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu0000000000'列不允许空值。插入失败。”考虑到OP想要循环(这在SQL Server中似乎是个坏主意)然后
行号
可能是更好的选择。标识
通常不是顺序的,这可能会导致循环过程出现异常行为。