sql-server - Export data from Microsoft SQL Server using a query to target data
问题描述
I know how to generate scripts to script insert lines allowing me to backup some data. I was wondering though if it was possible to write a query (using WHERE clause as an example) to target a very small subset of data in a very large table?
In the end I want to generate a script that has a bunch of insert lines and will allow for inserting primary key values (where it normally would not let you).
解决方案
If I read your requirement correctly, what you actually want to do is simply make a copy of some data in your table. I typically do this by using a SELECT INTO
. This will also generate the target table for you.
CREATE TABLE myTable (Column1 int, column2 NVARCHAR(50))
;
INSERT INTO myTable VALUES (1, 'abc'), (2, 'bcd'), (3, 'cde'), (4, 'def')
;
SELECT * FROM myTable
;
SELECT
*
INTO myTable2
FROM myTable WHERE Column1 > 2
;
SELECT * FROM myTable;
SELECT * FROM myTable2;
DROP TABLE myTable;
DROP TABLE myTable2;
myTable will contain the following:
Column1 column2
1 abc
2 bcd
3 cde
4 def
myTable2 will only have the last 2 rows:
Column1 column2
3 cde
4 def
Edit: Just saw the bit about the Primary Key values. Does this mean you want to insert the data into an existing table, rather than just creating a backup set? If so, you can issue SET IDENTITY_INSERT myTable2 ON
to allow for this.
However, be aware that might cause issues in case the id values you are trying to insert already exist.
推荐阅读
- chilkat - 使用 Ssl = true 时,Chilkat Upload BeginUpdate 失败并显示“无法读取 TLS 记录 (2)”
- c++ - sqlite3_prepare() 中的分段错误取决于 sql 字符串
- excel - EXCEL VLOOKUP 参数近似值
- reactjs - 使用 React JS 在电子商务商店中管理商店产品的最佳方法?
- python - 使用 mocker.patch 重命名 pytesting 文件
- amazon-web-services - AWS-SAM:如何重新使用 Route53 域而不是重新创建它?
- asp.net-mvc - 在视觉工作室工作时,我们创建 Meta 类,为什么?
- javascript - 为什么即使我刚刚推送了一个新数组,嵌套数组的长度仍返回未定义?
- java - 如何在 PDF 文件的框中选择文本?
- c++ - 如何将包含一个数字的字符串转换为 C++ 中的向量,其中所有数字都是向量的元素