简体   繁体   中英

Create Table from Another Table - MYSQL to MSSQL conversion

I'm in the process of converting a database from MYSQL to MSSQL/TSQL, and I can't get the following MYSQL query to work in MSSQL. Looking for a fresh set of eyes to see what I'm missing.

Working MYSQL Query:

CREATE TABLE tempTable 
AS (SELECT * FROM Note WHERE createdate IN (SELECT MAX(createdate) 
FROM Note GROUP BY `taskPK`));

The query looks for the max date of a note row for a given id. There may be multiple Note rows with the same ID and it will find the newest row and insert it into the new table.

Non-Working MSSQL Example 1: (Incorrect Syntax near '(')

CREATE TABLE tempTable 
AS(SELECT * FROM dbo.Note WHERE createdate IN (SELECT MAX(createdate) 
FROM dbo.Note GROUP BY taskPK));

Non-Working MSSQL Example 2: (Incorrect Syntax near the keyword INTO)

SELECT * 
FROM Note 
WHERE createdate IN (SELECT MAX(createdate) FROM Note GROUP BY taskPK) 
INTO tempTable FROM Note;

This new table (once created) will be used in the following query (which I haven't tested yet in MSSQL):

SELECT Task.id, Task.taskdescription, Task.status, TaskSchedule.date, TaskGroups.name, tempTable.createDate FROM Task 
LEFT JOIN TaskSchedule ON Task.id = TaskSchedule.taskPK
LEFT JOIN TaskGroups ON Task.taskgroupid = TaskGroups.id
LEFT JOIN tempTable ON Task.id = tempTable.taskPK
WHERE Task.userPK = '$userPK' AND Task.status = 'Open'
ORDER BY tempTable.createDate DESC;

The above query selects a task that includes the newest note from the previous query I'm having problems with -- adding this incase I'm making this more difficult than it needs to be.

You can't use Create table as or Select table into in mssql

Use:

SELECT * INTO tempTable FROM Note N
WHERE N.createdate IN (SELECT MAX(N1.createdate) FROM Note N1 GROUP BY N1.taskPK)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM