How to truncate the text in columns using SQL

Posted on 2007-10-02
Last Modified: 2010-08-05

I have a table in SQL Server with the following columns:
ID (identificator)
FileName nvarchar(100)  ' ( e.g. file_name.ext)
FileExtension char(3)  '(e.g. pdf, exe, doc, etc)

How can I truncate the file name using SQL and leave only the name in the FileName column and shift 'ext' into FileExtension column?

Question by:Zaurb
    LVL 142

    Accepted Solution

    update yourtable
       set FileExtension = right(FileName, 3)
        , FileName = left(FileName, len(FileName)-4)
    LVL 1

    Author Comment

    Thanks! That's exactly what I wanted!
    LVL 1

    Author Comment

    I know the question is closed, but how do I handle files in the same database with only 2 character extensions?
    LVL 142

    Expert Comment

    by:Guy Hengel [angelIII / a3]
    here is the generic version to get the last '.' in the name:

    update yourtable
       set FileExtension = right( FileName ,charindex('.', reverse(FileName ))-1)
        , FileName = left(FileName ,  len(FileName ) - charindex('.', reverse(FileName )))
    LVL 1

    Author Comment

    Great! Thank you very much! Where can I get all this information so fast? Thanks again!

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Looking for New Ways to Advertise?

    Engage with tech pros in our community with native advertising, as a Vendor Expert, and more.

    Suggested Solutions

    Entering time in Microsoft Access can be difficult. An input mask often bothers users more than helping them and won't catch all typing errors. This article shows how to create a textbox for 24-hour time input with full validation politely catching …
    Creating and Managing Databases with phpMyAdmin in cPanel.
    Video by: Steve
    Using examples as well as descriptions, step through each of the common simple join types, explaining differences in syntax, differences in expected outputs and showing how the queries run along with the actual outputs based upon a simple set of dem…
    Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

    759 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    10 Experts available now in Live!

    Get 1:1 Help Now