简体   繁体   中英

Insert query in SQL Server 2005

My SQL Server table structure is:

BranchName
BranchManagerName
Address
Zip Info
PhoneNo
FaxNo
Email
Status
CreatedOn

Now I try to pass the value for Zip Info column like State=XXXX , city=YYYY , Zip=123 as three values.

And I need these three values ( State,City,Zip ) stored in the Zip Info column in this format state,city-Zip ( xxxx,yyyy-123 ) in sql table.

How to write insert query in SQL Server 2005?

NO NO NO NOOOOOOO!!!

don't do it!! save them as individual columns. Never store multiple fields within a single column!

You'll have problems trying to select all rows for State='NY' , where you'll need to constantly do string manipulations and have slow non-index searches.

store them as separate columns and concatenate them when you display them.

SELECT
    ISNULL(State,'')+ISNULL(', '+city,'')+ISNULL('-'+Zip,'') AS ZipInfo
    FROM YourTable

you can always concatenate strings in an insert:

INSERT INTO YourTable
        (col1, col2, col3, Col123)
    VALUES
        (@col1, @col2, @col3, @col1+', '+@col2+'-'+@col3)

your "null protection" will vary as necessary, in the SELECT, I assume you could have NULL values, in the INSERT I assume there will be no NULL values.

Your would be much better off if you store them as 3 columns and create a view or computed column if you really want them as a single field. You are embarking on a common bad design issue by trying to store the values together.

look here for fun splitting strings in SQL Server!

Also, don't put spaces in your column names, unless [you like] having [braces] all [over the] place.

I agree with @KM. that you should not store this data in the same field. You will have significant problems searching for your data if you store the Zip Info data in the same field so you should NOT do it this way.

But if you must then you would have an insert similar to this:

INSERT INTO yourTable
(
    BranchName
    , BranchManagerName
    , Address
    ,[Zip Info]
    ,PhoneNo
    , FaxNo
    , Email
    ,Status
    , CreatedOn
)
SELECT  BranchName
    , BranchManagerName
    , Address
    ,State + ', ' + City + '-' + Zip
    ,PhoneNo
    , FaxNo
    , Email
    ,Status
    , CreatedOn

Bro, if you want to add value in format state,city-Zip for the field zip_info and the values for the state,city and zip are as follows XXX,YYYY,123 You just need to put all three values in the below format on the place of Zip_Info in the insert statement

'XXX,YYYY-123'

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