简体   繁体   中英

Import only certain records based on a criteria into a SQL server database

In a previous question i asked how to import the first 1000 rows in sql server from a csv file. Link to my previous question

Now i would like to know is it possible to import only certain records based on a certain criteria. For instance one column in my csv file is called Style. And i want to import all records where the style is equal to "ALE22".

Here is the code that works for me so far,

USE MyDB
BULK INSERT MyTable
FROM 'C:\Users\jasons\Desktop\Documents\MyFile.csv'
WITH(
FIRSTROW = 2,
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n',
LASTROW = 1002
)

You might be able to do this in one statement using the openrowset bulk provider, but you will have to specify a format file to describe the column names and delimiters.

insert into x (
    v1, v2
) select top 1000
    *
from
    openrowset(bulk 'C:\Users\jasons\Desktop\Documents\MyFile.csv',
        formatfile = 'path_to_ff',
        firstrow = 2
    ) x
where
    x.Style = 'ALE22';

There are also text providers for openrowset that you could investigate.

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