Create a new table and adding a data from old one in SQL Server 2017 in one query

北城余情 提交于 2019-12-25 18:22:07

问题


I have a main table that contains all cities and regions in Switzerland.

I want to create a table for each city, and copy the city data directly from the main to the new one according to its abbreviation.

For example, create a table for Zurich and copy all data from the old table when the abbreviation is ZH. create a table for Schaffhausen and copy all data from the old table when the abbreviation is SH.

I've used the following query, but did not work:

CREATE TABLE Zurich AS SELECT * FROM [dbo].[Post Code]
WHERE abbreviation = 'ZH'

回答1:


As you are saying, you wan to create table and it's data based on abbreviation so you should use abbreviation instead of Canton and you should us INTO in SQLSERVER. You can use CREATE TABLE <table_name> AS in MYSQL and other databases

SELECT * INTO Zurich FROM [dbo].[Post Code]
WHERE Abbreviation = 'ZH'



回答2:


Thanks guys, I found the solution.

USE [Post Code];  
GO  
CREATE TABLE dbo.Zurich  
( PostCode   int,  
  Place nvarchar(25),
  Canton nvarchar(50)  ,
  Abbreviation nvarchar(2),
  Country nvarchar(11)
);  
GO  
INSERT INTO dbo.Zurich  
    SELECT *   
    FROM [dbo].[Post Code] WHERE Abbreviation = 'ZH';  
GO 

Source



来源:https://stackoverflow.com/questions/51737348/create-a-new-table-and-adding-a-data-from-old-one-in-sql-server-2017-in-one-quer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!