我有一个SQL命令,可以从秒转换为HH:MM:SS。它创建新表,因为它从原始表中获取秒数。有没有办法在创建新表时设置name列的主键?这是我正在使用的SQL:
mso-header: url(\"mydocument_files/headerfooter.htm\") h1;
mso-footer: url(\"mydocument_files/headerfooter.htm\") f1;
我知道我可以创建另一个alter table命令,为我设置它:
SELECT
main.[Name],
RIGHT('0' + CAST(main.[Staffed Time] / 3600 AS VARCHAR), 2) + ':' +
RIGHT('0' + CAST((main.[Staffed Time] / 60) % 60 AS VARCHAR), 2) + ':' +
RIGHT('0' + CAST(main.[Staffed Time] % 60 AS VARCHAR), 2) AS StaffedTime,
RIGHT('0' + CAST(main.[Time in Break] / 3600 AS VARCHAR), 2) + ':' +
RIGHT('0' + CAST((main.[Time in Break] / 60) % 60 AS VARCHAR), 2) + ':' +
RIGHT('0' + CAST(main.[Time in Break] % 60 AS VARCHAR), 2) AS BreakTime,
RIGHT('0' + CAST(main.[Time in Lunch] / 3600 AS VARCHAR), 2) + ':' +
RIGHT('0' + CAST((main.[Time in Lunch] / 60) % 60 AS VARCHAR), 2) + ':' +
RIGHT('0' + CAST(main.[Time in Lunch] % 60 AS VARCHAR), 2) AS LunchTime
INTO
DailyReport
FROM
main
我希望有一种方法可以让它在创建后立即设置PK,这可能吗?
答案 0 :(得分:3)
在插入数据之前,尝试使用PRIMARY KEY
设置创建新的表变量。
请尝试下面的代码
CREATE TABLE DailyReport (
ID INT Primary Key IDENTITY(1,1),
[Name] NVARCHAR(30) ,
StaffedTime NVARCHAR(30),
BreakTime NVARCHAR(30),
LunchTime NVARCHAR(30)
)
INSERT INTO DailyReport
SELECT main.[Name],
RIGHT('0' + CAST(main.[Staffed Time] / 3600 AS VARCHAR),2) + ':' +
RIGHT('0' + CAST((main.[Staffed Time] / 60) % 60 AS VARCHAR),2) + ':' +
RIGHT('0' + CAST(main.[Staffed Time] % 60 AS VARCHAR),2)
AS StaffedTime,
RIGHT('0' + CAST(main.[Time in Break] / 3600 AS VARCHAR),2) + ':' +
RIGHT('0' + CAST((main.[Time in Break] / 60) % 60 AS VARCHAR),2) + ':' +
RIGHT('0' + CAST(main.[Time in Break] % 60 AS VARCHAR),2)
AS BreakTime,
RIGHT('0' + CAST(main.[Time in Lunch] / 3600 AS VARCHAR),2) + ':' +
RIGHT('0' + CAST((main.[Time in Lunch] / 60) % 60 AS VARCHAR),2) + ':' +
RIGHT('0' + CAST(main.[Time in Lunch] % 60 AS VARCHAR),2)
AS LunchTime
FROM main
SELECT * FROM DailyReport
答案 1 :(得分:1)
试试这个......
ALTER TABLE DailyReport
ADD CONSTRAINT PK_Name PRIMARY KEY (Name);
答案 2 :(得分:1)
无法自动创建primary key constraint
。你要么:
OR
SELECT INTO
表并通过添加PK约束(ALTER TABLE ... ADD CONSTRAINT PK_tablename PRIMARY KEY (col_name)
)提示:尝试始终使用命名约束,因为如果名称已修复(不是服务器生成),则更容易更改(删除)