ok Im sure this is simple. what is the command to execute a replace in a select statement
SELECT CUSTOMER.customer_id, CUSTOMER.full_name, CUSTOMER.main_address_1, CUSTOMER.main_address_2
FROM CUSTOMER
WHERE (((CUSTOMER.main_address_1) Like '%road%'))
???Replace all instences of road with RD???
can some one help on this one or even a refrence for research (besides BOL or Technet)
WHILE PATINDEX('%,%',@Columns)<> 0 BEGIN SELECT @Separator_position = PATINDEX('%,%',@Columns) SELECT @array_Value = LEFT(@Columns, @separator_position - 1) SET @FieldTypeID = (SELECT FieldTypeID FROM [Form].[Fields] WHERE FieldID = (CAST(@array_Value AS INT))) SET @FieldName = (SELECT [Name] FROM [Form].[Fields] WHERE FieldID = @array_Value) print 'arry value' + CONVERT(VarChar(500), @array_value) print 'FieldTypeID: ' + CONVERT(VARCHAR(500), @FieldTypeID) PRINT 'FieldName: ' + @FieldName
BEGIN IF @FieldTypeID = 1 OR @FieldTypeID = 2 OR @FieldTypeID = 3 OR @FieldTypeID = 9 OR @FieldTypeID = 10 OR @FieldTypeID = 7 BEGIN SET @InnerItemSelect = ' (SELECT ISNULL(CONVERT(VARCHAR(MAX),[Value]),'''') FROM [Item].[ItemDetailFieldRecords] IDFR WHERE IDFR.ItemDetailID = ID.ItemDetailID AND IDFR.FieldID = ' + @array_Value + ') AS ''' + @FieldName + ''' ' SET @InnerTaskSelect = ' (SELECT ISNULL(CONVERT(VARCHAR(MAX),[Value]),'''') FROM [Item].[TaskFieldRecords] TFR WHERE TFR.TaskID = T.TaskID AND TFR.FieldID = ' + @array_Value + ') AS ''' + @FieldName + ''' ' END ELSE IF @FieldTypeID = 4 OR @FieldTypeID = 8 --DropDownList/RadioButtonlist BEGIN SET @InnerItemSelect = ' (SELECT [Value] FROM [Form].[FieldListValues] FFLV INNER JOIN [Item].[ItemDetailFieldListRecords] IDFLR ON FFLV.FieldListValueID = IDFLR.FieldListValueID WHERE IDFLR.ItemDetailID = ID.ItemDetailID AND FFLV.FIeldID = ' + @array_value + ') AS ''' + @FieldName + ''' ' SET @InnerTaskSelect = ' (SELECT [Value] FROM [Form].[FieldListValues] FFLV INNER JOIN [Item].[TaskFieldListRecords] TFLR ON FFLV.FieldListValueID = TFLR.FieldListValueID WHERE TFLR.TaskID = T.TaskID AND FFLV.FIeldID = ' + @array_value + ') AS ''' + @FieldName + ''' ' END ELSE IF @FieldTypeiD = 5 --Cascading BEGIN SET @InnerItemSelect = ' (SELECT [FCV].[Value] FROM [Form].[FieldCascadingValues] FCV INNER JOIN [Form].[FieldCascadingLookUpTables] LT ON FCV.FIeldCascadingLookupTableID = LT.FieldCascadingLookupTableID INNER JOIN [Item].[ItemDetailFieldCascadingRecords] IDFCR ON IDFCR.FieldCascadingValueID = FCV.FieldCascadingValueID WHERE IDFCR.ItemDetailID = ID.ItemDetailID AND LT.FieldID = ' + @array_value + ') AS ''' + @FieldName + ''' ' SET @InnerTaskSelect = ' (SELECT [FCV].[Value] FROM [Form].[FieldCascadingValues] FCV INNER JOIN [Form].[FieldCascadingLookUpTables] LT ON FCV.FIeldCascadingLookupTableID = LT.FieldCascadingLookupTableID INNER JOIN [Item].[TaskFieldCascadingRecords] TFCR ON TFCR.FieldCascadingValueID = FCV.FieldCascadingValueID WHERE TFCR.TaskID = T.TaskID AND LT.FieldID = ' + @array_value + ') AS ''' + @FieldName + ''' ' END ELSE IF @FieldTypeiD = 6 --ListBox BEGIN SET @InnerItemSelect = ' (SELECT i.[CSV] FROM @ItemDetailLV i WHERE i.ID = ID.ItemDetailID AND i.FieldID = ' + @array_value + ') AS ''' + @FieldName + ''' ' SET @InnerTaskSelect = ' (SELECT it.[CSV] FROM @TaskLV it WHERE it.ID = T.TaskID AND it.FieldID = ' + @array_value + ') AS ''' + @FieldName + ''' ' END ELSE IF @FieldTypeID = 11 --Users BEGIN SET @InnerItemSelect = ' (SELECT SU.[UserID] FROM [Security].[Users] SU INNER JOIN [Item].[ItemDetailUserRecords] IDUR ON SU.UserID = IDUR.UserID WHERE IDUR.ItemDetailID = ID.ItemDetailID AND IDUR.FieldID = ' + @array_value + ') AS ''' + @FieldName + ''' ' SET @InnerTaskSelect = ' (SELECT SU.[UserID] FROM [Security].[Users] SU INNER JOIN [Item].[TaskUserRecords] TUR ON SU.UserID = TUR.UserID WHERE TUR.TaskID = T.TaskID AND TUR.FieldID = ' + @array_value + ') AS ''' + @FieldName + ''' ' END ELSE IF @FIelDTypeID = 12 --Group BEGIN SET @InnerItemSelect = ' (SELECT SG.[GroupID] FROM [Security].[Groups] SG INNER JOIN [Item].[ItemDetailGroupRecords] IDGR ON SG.GroupID = IDGR.GroupID WHERE IDGR.ItemDetailID = ID.ItemDetailID AND IDGR.FieldID = ' + @array_value + ') AS ''' + @FieldName + ''' ' SET @InnerTaskSelect = ' (SELECT SG.[GroupID] FROM [Security].[Groups] SG INNER JOIN [Item].[TaskGroupRecords] TGR ON SG.GroupID = TGR.GroupID WHERE TGR.TaskID = T.TaskID AND TGR.FieldID = ' + @array_value + ') AS ''' + @FieldName + ''' ' END END PRINT 'Inner Item Select:' + @InnerItemSelect PRINT 'Inner Task Select:' + @InnerTaskSelect SET @IDSelect = @IDSelect + @InnerItemSelect + ', ' SET @TSelect = @TSelect + @InnerTaskSelect + ', ' SELECT @Columns = STUFF(@Columns, 1, @separator_position, '')
END
---------------
That is only part of a large query that writs a SQL Query to a column in a Database. That Query (in the column) is just ran normally so I don't need to compile it each time I want to run it.
THe problem I have is @FieldName might be: ryan's field.
That apostrophe is killing me because the SQL keeps it as ryan's field, not ryan''s field(note the 2 apostrophes). I cannot do: REPLACE(@FieldName, ''', '''') because it's not closing the apostrophes. Is there an escape character that I can use to say only one: ' ?
I tried:
DECLARE @t VARCHAR(500) SET @t = (SELECT [Name] FROM [Form].[Fields] WHERE FieldID = 1) print @t -- @t will print: Ryan's Field PRINT QUOTENAME('' + @t + '', '''')
but that gives me: 'Ryan''s Field'
Any help would rock. If I make any changes to the way this field is input into the DataBase, I know I will need to do a lot of re-work in many spots. WHich is why i'm trying to solve this on the SQL side.
I have text data files from a third party and they use comma as field delimiters and enclose the text for each column in double-quotes. Not a problem for most of the data files until they start sending files where there is " within the column values. SSIS package fails with the error:
The column delimiter for column "Column 1" was not found.
Any ideas on how to resolve this issue will be greatly appreciated.Thankspcp
I have followed many tutorials on selecting and replacing text in text fields, varchar fields and char fields, but I have yet to find a single script that will to all 3 based on field type. Let's assume for a moment that I don't know where all in my database a certain value that I need changed resides ... i.e., the data's tablename and fieldname. How would I go about doing the following ... or more importantly, is this even possible in a SQL only procedure?1) Loop over entire database and get all user tables2) Loop over all user tables and get all fields3) Loop over all fields and determine the field type4) switch between field types and change a string of text from 'a' to 'b'Please be gentle, I'm a procedure newb.
Hello,I'm trying to update a single field of a record and i want to do it using a standard multi line text box but I'm not sure how to write the c# command to process the sql update. I would also like the entry to be added into the database with line breaks. Thanks for your help
Hi all SSIS experts, I have a task to read certain columns from the db, convert it into a tab delimted text file and post it in an FTP site. Please suggest on the steps to accomplish this. Is SSIS the best way? Can the same task be accomplished using only sql code. Regards, Josiny
How can I program BCP to output text items in double quotes (")? Here is an example (please try it) that trys to output some columns from a table to csv file. However, due to the existence of commas within the fields, the comma separation gets messed up.
------------------------------------ USE [MASTER]
IF EXISTS (SELECT 1 FROM sysobjects WHERE name = 'mcg1') DROP TABLE mcg1 go
CREATE TABLE mcg1 (pkINT IDENTITY(1,1) ,Address_1VARCHAR(100) ,CityVARCHAR(100)) go
Exec Master..xp_Cmdshell 'bcp "SELECT Address_1, City FROM mcg1" queryout "C:mcg1.csv" -c -t,"'
------------------------------------ The output I get is below. You can see how the use of commas in the text makes the comma separate list all confused 100 Road1, Suburb1,BigCity1 200 Road2, Suburb2,BigCity2
Thus what I want is "100 Road1, Suburb1","BigCity1" "200 Road2, Suburb2","BigCity2"
You can do this OK in DTS by specifying the text identifier to be double-quotes. I do NOT want to use DTS and want to be able to do via a T-SQL procedure. Note that the real table I will export from has numeric datatypes and I would prefer NOT to wrap them in double-quotes too.
Thus, how can I alter the Exec Master..xp_Cmdshell command, to wrap each text field in double quotes. I may have to use a format file in which case please provide the format file too.
We have an issue with importing a CSV file into SQL where using a double quote " text qualifier is failing. The data is correct but it fails on a particular line, complaining about the qualifier even though the qualifier is in place and previous lines have imported fine.
Hi. I am currently building a blog application, and I need some advice... I have the post title, post date, post by, etc stored in a database table, however I was wondering whether I should store the actual post content in the database as well or in a text file. For example, if the posts get really long would it slow down database performance or would there not be much of a difference? Furthermore, if I wanted to keep the posts private, a text file would not be ideal as it can be accessed easily by surfers... What do you recommend?Thanks a lot
I had a situation that required me to set up SQL Server to do full text search against both English content and Chinese content. I am not sure if it's achievable in SQL server environment. Any help is appreciated.
I am performing a series of calculations where accuracy is very important, so have a quick question about single vs double precision variables in SQL 2008.
I'm assuming that there is an easy way to cast a variable that is currently stored as a FLOAT as a DOUBLE prior to these calculations for reduced rounding errors, but I can't seem to find it.
I've tried CAST and CONVERT, but get errors when I try to convert to DOUBLE.
For example...
SELECT CAST(1.0/7.0 AS FLOAT) SELECT CONVERT(FLOAT, 1.0/7.0)
both give the same 6 decimal place approximation, and the 6 decimals make me think this is single precision.
But I get errors if I try to change the word FLOAT to DOUBLE in either one of those commands...
Every night we connect to a remote server using Linked Server and copy details from that database to a loading table, then load it into the 'real' table in our own environment. The remove database we load it from has indexes/primary keys that match the 'real', however the 'loading' table itself does not have any indexes or primary keys, both are SQL Server 2005 machines.
In the loading table we first of all truncate it then do a select insert statement from the remote server, then we then truncate the 'real' table and load iit from the 'loading' table.
The issue is when we attempted to load it into our 'real' table from our loading table there was a duplicate row, and our process failed with a Primary Key violation.
I checked the source with does have the same primary key's in, it did not contain a duplicate row and I checked the loading table and that did contain a duplicate row.
My question this is in what circumstances this could happen ?
Here is my issue i have email addresses in a column of a table in sql server. Are addreses has changed since and i need to do a mass update of these email addreses i need to replace a few char to reflect this change like ex:
AAAAA@BBB.CCC.Com i need to replace the BBB. part with nothing so that it looks like this AAAAA@CCC.Com.
sunil writes "hi, i have a problem when i updating record in the database. i am trying to insert value ('Company's Director') in the field but i receive an error Incorrect syntax near 's' what do i do for this error.i want to value like as ('Company''s Director'). please solve my problem"
I’ve created a script which will do the following.
Update fields in a database which contain instances of an order number. An order number is defined as a 10 digit numeric sting which beings with 998. The first 3 digits of the order number need to change from 998 to 999. There are two types of fields to update: document number fields which may contain 1 instance of the order number and free text fields which may contain multiple instances of an order number.
I created a function which accepts the text to be updated, the text to find and the text to replace it with. The function then loops through the sting for instances of 998. For each instance it finds it checks to ensure that it is at the start of a 10 digit string which contains only numeric numbers – if this is the case then it will update the 998 to be 999. If the field is free text then it will continue to loop through the string (it will skip forward 10 digits for every order number found) until the end. If the field is not free text then it will exit the script after the first instance found which matches the above criteria, if any.
Need achieving this via set processing and not having to loop through every line. I’ve included the function below and some test data.
--Create the function we will call in order to do the replace if object_id(N'OrderReplace',N'FN') is not null drop function dbo.OrderReplace; go create function dbo.OrderReplace ( @Textnvarchar(4000),
I am working with a database named €œDocuments€? that contains 4 categories of text documents, each having its own number designation in an integer datatype column named SectionTypeId:
1 = Text 2 = Report 3 = Background 4 = Index
I would like to create a new column named €œDocType€? in which the integer data type for each document is replaced with a varchar data type letter (1 = T, 2 = R, 3 = B, 4 = I). I was able to easily create the new column and cast the data type from integer to varchar:
--CREATE NEW COLUMN €œDocType€? WITH VARCHAR DATATYPE
ALTER TABLE FullDocuments ADD DocType VARCHAR(1) NULL Go
--UPDATE NEW COLUMN WITH CAST STRING
UPDATE FullDocuments SET DocType = CAST(SectionTypeID AS VARCHAR(1)) Go
But I have problems with the REPLACE method for replacing the numbers with letters. First I tried this based on the examples in MSDN Library:
--REPLACE NUMBERS WITH LETTERS
UPDATE Fulldocuments REPLACE (DocType,"1","T")
Which produced an error message: €œIncorrect syntax near 'REPLACE'.€?
Thinking that the datatype may be the problem, I tried this to convert to DT_WSTR data type prior to replace:
--------------------------------------------------------------- My Original Post I have to query n table(NLRImports) using the Distinct keyword, to retrieve a set of ID numbers. ( "Select DISTINCT id_nbr from NLRImport" ).
Now i want to use those values i retrieved, to process the records in the table(NLRImports) 1 by 1. How do i use those ID no's i retrieved as Variables or parameters for my next query?? If this makes sense? ----------------------------------------------------------------
First, thanks for the response.... now here is what im trying to do. I created a simple application in delphi to import information to a table in MSSql2005. This is some of the resulting columns...
Now there will be several entries with the same id no but on different dates, so i take it dates would rather be my pkey.
Then i need to take one person's entries(i work on id_nbr) and go thru all the entries taking the earliest date and comparing all the other entries for that person to the first date and select all the dates more than 19 days after the first date and less than 91 days from first date and place it in a new table. I used cursor s and while loops to kind of get it going but i know that cursors are not really recommended use but the performance implications dont bother with this particular job.
What other ways should i be using to accomplish this?
I have a table that has a Text datatype column that has gotten somegarbagecharacters in it somehow, probably from key entry. I need to removethe garbage, multiple occurances of char(15). The replace functiondoes not work on Text datatype. Any suggestions?
I have a SQL Server 2005 database that has a table with a TEXT column. This TEXT column has XML data in it. The length of the XML data in each record in the table is about 700,000 characters. What is the quickest most efficient method to replace a nodes text with another value? I.E., <LogoLarge>aasdfasdfaasadfasdfsdfasdfadsf</LogoLarge> with <LogoLarge>a</LogoLarge>. This table has about 2 million records. Thanks in advance for your help.
There are plenty of scripts to do this on a per-DB level, but any that will allow me to generate a script for all DB's at once? Mine are split across dozens and it would be much easier to do a loop (using MS_ForeachDB ? )
I have a text field with about 17,500 rows I need to edit from for example: '1.90X .90' to '1.90X 0.90'? The numbers are various but follow the basic format albiet they may vary to say '22.78X .40'
I have a string column in a DB where it's values contain the following midway through the string ([DOCUMENTGUID] is a uniqueidentifier that is different for each row):
I've got an nvarchar(max) column that I need to transform with some simple text processing: insert some markup at the very beginning, and insert some markup just before a particular regular expression is matched (or at the end, if no match is found).
Since the SSIS expression language doesn't support anything like this, is a Script Component the only way to go? Does Visual Basic .NET provide regular expression matching?
We have a legacy database that have hundreds of stored procedures.
The previous programmar uses a string like servername.databasename.dbo.tablename in the stored procedures. We now have migrated the database to a new server. The old server is either needed to be replaced by the new server name, or remove it.
I don't know why he used servername as part of the fully qualified name, we don't use linked servers. So I think better removing the servername in all the stored procedures.
I know I can do a generate script, and replace the text and then use alter procedure to recreate all the stored procedures. But since hundreds of them, is there a programmatically way to replace them?
I've never used SQL for anything but simple copies and queries, and now I need to do something that's probably simple, as well, but I don't know how to start. I need to update values in a text field with new values from another table. I can do it individually with an update statement (Set [field1] = 'newvalue' where [field1] = 'oldvalue'). But I have 400 different values and a bunch of different tables that need to be updated, and can't imagine that's the only solution. I can make up a simple table that will have all the old values in one column, and the new values in the next. I need a statement that look at the old value, then fetch the new value from the table I made, and replace the old value with the new.
I've looked at various help files and tried to search for a solution elsewhere, but I'm not coming up with anything. I guess I just don't know where to look. Thanks in advance for any help you can give me.
Alright so here is what I am trying to do. I have a form that someone fills out it has a text box as title, and a drop down box that is a category, and then a text area that is for their explanation. On the back end I am using a stored procedure called sp_store_bkm. When I execute this it works just fine and puts the data that I put in it into the to table below is the Stored procedure code: ALTER PROCEDURE sp_store_bkm @oID nvarchar OUTPUT, @oTitle nvarchar(50), @oCategory nvarchar(50), @obkmtext nvarchar(MAX) AS BEGIN INSERT INTO tbl_bkms(Title, Category, bkmtext) VALUES(@oTitle, @oCategory, @obkmtext)Set @oID= SCOPE_IDENTITY() END
Now on my front end it comes up with an error in the lower left (erros on page). When I click on the error for details it seems like it is coming fromt he connection string. I cant find anything wrong with the connection string. Below is my code for the aspx page. <%@ Page Language="VB" MasterPageFile="~/MasterPage.master" Title="Untitled Page" %><asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> <script> function Submit2_onclick() { Dim Connection As SqlConnection = "server=localhost;Database=BKM.mdf;integrated security=SSPI;" connection.Open() Try Dim command As SqlCommand = New SqlCommand("sp_store_bkm", connection) command.CommandType = CommandType.StoredProcedure Dim oID As New SqlParameter("@oID", SqlDbType.Int) oID.Direction = ParameterDirection.Output command.Parameters.Add(oID) command.Parameters.Add("@oTitle", title.text) command.Parameters.Add("@oCategory", category.text) command.Parameters.Add("@obkmtext", bkmtext.text) command.ExecuteNonQuery() Dim sOrderID As String = oID.Value }</script> <form method="post"> <table cellpadding="10" style="width: 100%"> <tr> <td style="width: 100px"> <span style="font-size: 10pt; font-family: Verdana"> Login ID: <br /> </span> <asp:LoginName ID="LoginName1" runat="server" Font-Names="Verdana" Font-Size="10pt" ForeColor="Red" /> <span style="font-size: 10pt; font-family: Verdana"> <br /> <br /> Title:<br /> </span> <input id="title" style="width: 374px" type="text" /><br /> <br /> <span style="font-size: 10pt; font-family: Verdana"> Category:<br /> </span> <select id="Category" name="D1" size="1" language="javascript" onclick="return Select1_onclick()"> <option selected="selected">Office Applications</option> <option>VPN</option> <option>WLAN</option> </select> <br /> <span style="font-size: 10pt; font-family: Verdana"> <br /> Your BKM<br /> </span> <textarea id="bkmtext" style="width: 378px; height: 196px"></textarea><br /> <br /> <input id="Reset1" type="reset" value="reset" /> <input id="Submit2" type="submit" value="submit" language="javascript" onclick="return Submit2_onclick()" /></td> </tr> </table> </form></asp:Content>
I am a student at DePaul University in Chicago, IL. We have a big db project tomorrow and I'm proud with the work I've done so far, I've designed my own db and tested it using queries and such. Pretty good for being introduced to SQL just a couple short months ago. Anyway, I've sort of run into a wall here. I need to have an attribute of a table be computed from others.
I'm working with 2005 Server Management Studio and I have found the computed column specification under the column properties tab. I know that I have to enter a formula, but I'm just not sure on what to do. I have a CHG_HOUR attribute in a table called "EXPERTISE" which signifies how much a consultant charges per hour, based on what he exactly does. I also have a JOB_HOURS attribute in a JOB table (that links my CONTRACT table to CONSULTANT). I want to basically give a formula that multiplies the CHG_HOUR from the EXPERTISE table by the JOB_HOURS in the JOB table. Any suggestions on how I might do this?
Thank you in advance for your response, and hopefully with more practice and courses, I can be the one helping people like me on these boards in a few years.