hey all
i am stuck with this little problem
I have a table with people's names and addresses and i have one column for the zip codes. sometimes it includes 5 digit zip codes like '70820' and some times it includes all nine digits like '70820-4565'
is there anyway to move the last 4 digits of the long zip codes into a new column? and remove the dash?
Hello. I have a column in my database which is holding phone number. The problem is that although I gave the number starting with zero but it will erase it automatically. So can you help me to solve this problem? Thank you
Help, I'm stuck! I have a Customer table:ID Name-- ---------------------1234 Christopher's Surf Boards4321 Christina's NailsI have to build a Account table:ID GPID-- --------------------1234 CHRIST004321 CHRIST01I've built a function that gives me the six alphas and concatenates thetwo digits. The GPID in the account table is the first six alphas ofthe company name plus two digits to ensure uniqueness. (Don't ask why Ican't use the existing id -- the story is long and boring.) I built afunction that creates the alpha part and assigns the first 00. I builta second function that I thought would check the Account table as I wasinserting and increment the numbers if the account number alreadyexisted. It doesn't work. In the above table, both IDs come out asCHRIST00. Here's the second function:ALTER FUNCTION fnValidateID(@mString varchar(15))RETURNS varchar(15)ASBEGINDECLARE@sTemp varchar(15),@sInc varchar(2),@iInc intBEGINset @sTemp = @mStringwhile exists (select GPID from dbo.tempID where GPID = @sTemp)beginset @iInc = convert(int,right(@mString,2)) + 1set @sInc = convert(varchar(2),@iInc)if len(@sInc) < 2 set @sInc = '0' + @sIncset @sTemp = substring(@sTemp,1,len(@sTemp) - 2) + @sIncend--NEXTENDRETURN @sTempENDMy first guess is that the code is okay, so far as it goes, but that Ican't check the values in the table at the same time I'm inserting intoit. (The Account table is empty, initially.) In any case, I can'tfigure out where I've gone wrong.Thanks.
I'm needing help with the following check digit calculation.
I have a Table with the following columns
Newscan nchar(31) checkdigit nchar (10)
Newscan ex value 012345670 600888081 307051111
I need to multiply each character by the following sequence starting on the left alternating the multiplyer skipping spaces 21212121
if the multiplyed number is greater than 9 I need to add the two digits together. Ex 2X9 = 18 for a saved value of 9
I then need to add the entire string together divide that by 10 and take the right most character and subtract that from 10 to end up with a check digit number that I want to store in the column checkdigit.
I have a case statement that converts the alpha chars in the string to the correct numeric values but I'm lost after that on how to accomplish this.
Thanks in advance for any help or direction.
I tried to look at the bank routing check digit function but couldn't get to the code of it.
I am sure this will be an easy one for you pros, but I am having a case of the Mondays. I am trying to retrieve a date in the format 2007.01.01. In trying to do this I either end up with 1 or null when trying to create the 01 part. Below is some test code for the month portion.
how do i calculate all the checkdigits for a subset of ids and return all the ids and checkdigits? basic calculation isn't the problem, just how to select the ids and utilize the ids in the calc. I am new to trying to do calculations on data.
I have a table with a column 'zipcode' that contains a 9 digit zipcode. I am am trying to figure out how I can create a query that returns the count of the most popular zipcodes based only on the first 5 digits.
This is what I have
Code:
SELECT Customers.Zipcode, Count(Customers.Zipcode) AS CountOfZipcode FROM Customers GROUP BY Customers.Zipcode ORDER BY Count(Customers.Zipcode) DESC;
which does what I want it to do except it uses the whole 9 digits.
I have a field in a table that contains ten digit value representing a datetime. Is there any way to convert it to default datetime formatThanks--Message posted via http://www.sqlmonster.com
create function dbo.iso6346_char_to_number(@char char)returns intasbeginreturncase upper(@char)when '0' then 0when '1' then 1when '2' then 2when '3' then 3when '4' then 4when '5' then 5when '6' then 6when '7' then 7when '8' then 8when '9' then 9when 'A' then 10when 'B' then 12when 'C' then 13when 'D' then 14when 'E' then 15when 'F' then 16when 'G' then 17when 'H' then 18when 'I' then 19when 'J' then 20when 'K' then 21when 'L' then 23when 'M' then 24when 'N' then 25when 'O' then 26when 'P' then 27when 'Q' then 28when 'R' then 29when 'S' then 30when 'T' then 31when 'U' then 32when 'V' then 34when 'W' then 35when 'X' then 36when 'Y' then 37when 'Z' then 38endendcreate function dbo.iso6346_check_digit(@string char(10))returns charasbeginreturn (dbo.iso6346_char_to_number(substring(@string,1,1) )*1+dbo.iso6346_char_to_number(substring(@string,2,1) )*2+dbo.iso6346_char_to_number(substring(@string,3,1) )*4+dbo.iso6346_char_to_number(substring(@string,4,1) )*8+dbo.iso6346_char_to_number(substring(@string,5,1) )*16+dbo.iso6346_char_to_number(substring(@string,6,1) )*32+dbo.iso6346_char_to_number(substring(@string,7,1) )*64+dbo.iso6346_char_to_number(substring(@string,8,1) )*128+dbo.iso6346_char_to_number(substring(@string,9,1) )*256+dbo.iso6346_char_to_number(substring(@string,10,1 ))*512)%11end
I want to build a string that contains today's date (without the time).
For example, if select GETDATE() returns 2008-04-28 14:18:34.180, I want to end up with either
(1) 2008-04-28 or (2) 20080428. (I always want the month to be represented by a 2 digit number)
Is there a datepart parameter that will give me (1) in one shot? I don't think so, since datepart returns an integer and (1) is not in the form of an integer.
So, I was trying to build (2) by using the yyyy, mm, and dd parameters to extract out the appropriate parts and casting them to a string and contatentating them. However, when I do the month portion, (using mm) it gives me the integer that represents the month, and this number can be 1 or 2 digits depending on the month. I always want it to be a 2 digit number. For example, if I'm in Apr, I want to end up with "04", not "4". This would also apply to the day portion. (although the date that I'm writing this post is on the 28th so I'm not certain what GETDATE() will return on dates that are 1 digit.)
The only way I can get the single digit month to write out as a 2 digit month is by doing a LEN() function on the string and if it is a length 1, then concatenate a "0" in front of it. I started doing this and the expression became too crazy, so I wanted to first check to see if someone can come up with something cleaner.
I am currently working on an app and have an issue with a table in the database. The table has 10,000 records in it and a column is added that is to use a 4 digit in sequence. The datatype for the new column is varchar since no math will ever be done on the added column. If necessary, I can change the datatype but would prefer not to. The 4 digit would start with 0000 at ID 1 and go to 9999 at ID 10000. I'm thinking some type of update statement since it is updating each record but how would it be done sequentially?
I am retrieving the current month and setting a variable accordingly.
Code: DECLARE @currMonthNum INT SET @currMonthNum = DATEPART(MM, GETDATE())
My challenge is that at a later point I want to use the @currMonthNum value to 'build' a date in the style yyyymmdd and the variable is only one digit for the months January to September (e.g.: 1 to 9). For the months January to September I need to pad the variable with an extra zero (e.g.: 01 to 09).
Here is my attempt to do this...!
Code: IF @currMonthNum IN (1, 2, 3, 4, 5, 6, 7, 8, 9) SET @currMonthNum = '0' + CAST(@currMonthNum AS nvarchar)
Unfortunately this does not give the desired result of two digits, however ironically if I add a + '0' to the end I get 10 to 90! It is like the 0 at the front is simply being ignored.
I have also tried setting the @currMonthNum variable to an nvarchar type before performing the character addition as well attempting to use the CONCAT command (however I don't think that CONCAT can be used when setting a variable).
how to display a zero in front of the months that require it?
'code'- varchar 255 (Unique number) data : chr456Umx 'Packs'- integer data : 6
Is it posible to generate 13 digit number using the above two columns, The reason is if I run the procedure I will get same 13 digit all the time depending on the above two colums
below is the sample procedure I am using
CREATE PROCEDURE AMZSelCen @imglink nvarchar(255)
AS
Select code as sku, PdtBarCode as [standard-product-id], 'EAN' as [product-id-type],
--generate 13 digit number
make+' '+model+' ' +', Price for '+cast(NumPacks as varchar(8)) +' '+'Packs' as title, make as manufacturer,'
Using SQL Analyzer or .NET 2.0 programmatically, is there a way to get Transact SQL 2000 to not append a digit at the end of an identifier name when the result set has the same identifier multiple times (from a JOINed SELECT to various tables which have names in common and where I need to get all column names/values in one fell swoop)?
SELECT A.*, B.* from TableA A INNER JOIN TableB B on (A.Name = B.Name)
The result set will have NAME1 and NAME2, of course (or perhaps it's NAME and NAME1 -- no matter -- I wish to get rid of the numeric suffic).
I'm using a file Task to rename files to include a Month and Year in the FIle. Part of the requirement in the file name is a two digit month. I have the following query built which will return a two digit month regardless if it's a one or two digit month.
I have run into something really annoying. If I run the following SQL into SQL Server via SSMS it will load "31-DEC-49" as 2049-12-31. INSERT INTO Stg_StockProductCostPrice VALUES (0,9999,0.99,'15-NOV-75','31-DEC-49')
But if I have the same data in a file and load it via SSIS it is loading into the database as 1949-12-31, instead of 2049-12-31.
I know there is a property called "Two Digit Year Cutoff" against the server. It is defaulted to 2049. Is there anything similar within SSIS?
Hi , I have a database that records the users entrance to a building.The dates are recorded also .I have written some codes that to detect the period of dates that the person has entered.Lets say that a person named as jhon has entered the building on the days 02/08/2006 and 05/08/2006 and 11/08/2006 .Those dates are formated as dd/mm/yyyy . So that john has entered building for 3 times and the periods for the dates are one after another entrance is 3 days + 6 days =9 days .If you divide 9 by 3 we get the arithmetic average number 3 .So that we can say as john visits this building every 3 days and we can guess the next day that he may come. I have coded this and works great .I will paste the codes to the end of my message.But a master programmer friend of mine has said that I should have get this result by without writing code , by just using sql database .But some kind of stored procedure I mustn't use.So that I thought it can be done by views in sqldb .By using sql server enterprise manager I tried to use views but I could not succees. Can anyone guess this ? Here are my vb codes ... database data types : entry_id : int , identity user_id : int movie : nvarchar (50) dateenter : datetime stored procedure that selects the data from db: CREATE PROCEDURE veri_al ( @user_id int ) AS SELECT entry_id ,user_id, movie, dateenter from uye_aktiviteleri where (user_id=@user_id) ORDER BY entry_id ASC GO Code:Dim conn As New SqlClient.SqlConnection conn.ConnectionString = "data source=localhost;initial catalog=AFM;uid=nusret;pwd=araz" Dim command As New SqlClient.SqlCommand command.CommandText = "[veri_al]" command.CommandType = CommandType.StoredProcedure command.Connection = conn command.Parameters.Add("@user_id", SqlDbType.Int, 4).Value = Val(TextBox1.Text) If Not IsNumeric(TextBox1.Text) Then Exit Sub End If Try Dim adapter As New SqlClient.SqlDataAdapter adapter.SelectCommand = command Dim ds As New DataSet adapter.Fill(ds, "uyeler") DataGrid1.DataSource = ds.Tables("uyeler") Dim recordcount As Integer 'Found the recordcount recordcount = ds.Tables("uyeler").Rows.Count Dim mydatarow_ilk As DataRow Dim mydatarow_son As DataRow 'in stored procedure I used ORDER BY entry_id ASC so that first datarow 'will always be the first visit date and the last record of the 'datarow will be the last visit date mydatarow_first= ds.Tables("uyeler").Rows(0) mydatarow_last = ds.Tables("uyeler").Rows(recordcount - 1) Dim first_date As String Dim last_date As String first_date = mydatarow_first("dateenter") last_date =mydatarow_last("dateenter") Dim average_ As Integer 'What is the aveare of the visits ortalama = DateDiff("d", first_date , last_date ) / recordcount Label2.Text = "Member had visited for " & recordcount & "times" Label3.Text = "by average he/she comes here " & ortalama & " day to another." Dim last_time_visit As Integer last_time_visit = DateDiff("d", last-date , DateTime.Today()) Label4.Text = "Until the last visit it had been" & last_time_visit & " days" Label5.Text = "Guess for the next visit is" & DateAdd("d", average_ , last_date) ' MsgBox("average visits" & ortalama & " days" ) Catch z As Exception MsgBox("error : " & z.Message()) Finally MsgBox("Successfully calculated") End Try End Sub
Hi,I have a table of Locations around the country. My system produces reportsbased on these Locations. I also have a table containing Brick Codes e.g.Brick Post CodeAB51 AB51AB52 AB52AB55 AB55AB56 AB56AL01 AL1AL02 AL2AL03 AL3AL04 AL4How can I compare the first 3 or 4 letters of the postcode in the Locationstable to the corresponding entry in the Brick Codes table so I can add it tomy report?Thanks for your help
I have another question about ADO (using C++). I have searched the MSDN but I haven't found a answer to my question (maybe I'm just too stupid)... If I make a connection to my SQL Server there may occur some errors, but how to find out what went wrong ?
In terms of code I have e.g. something like that: try { connection->Open(ConnectionString,Username,Password,ADODB::adConnectUnspecified); ...} catch (_com_error& e) { long numErrors = connection->Errors->Count; for (long i=0; i<numErrors; i++) { ADODB::ErrorPtr pErr = connection->Errors->GetItem(i); ..... }}
Now I could get the error number by pErr->GetNumber(). But with which symbolic constant has this to be compared to find out which error occured ?? I didn't find any...Or is there another better way to do this ?
How can I test sql codes and don't want to connect to company database? My company is using sql server 2000. Below is the test codes which create a simple table, calculate and just want to check before writing more complicated codes.
create table EquipmentUptime ( equipmentId int not null ,transactionId int not null ,dateOccured datetime not null ) go -- insert into EquipmentUptime values (1,200,'01/01/2007') insert into EquipmentUptime values (2,200,'01/01/2007') insert into EquipmentUptime values (3,200,'01/01/2007') insert into EquipmentUptime values (2,100,'02/12/2007') insert into EquipmentUptime values (1,100,'02/25/2007') insert into EquipmentUptime values (3,100,'03/10/2007') insert into EquipmentUptime values (1,200,'03/14/2007') go -- select equipmentId ,100*(cast((cast(sum(UpDays)as decimal(6,3))/cast(365 as decimal(6,3))) as decimal(4,3))) 'PctUpTime' from ( select c.equipmentId ,datediff(dd,c.[UpDate],c.DownDate) 'UpDays' from ( select a.equipmentId ,a.dateOccured as 'UpDate' ,coalesce( (select top 1 b.dateOccured from EquipmentUptime b where transactionId=100 and b.equipmentId=a.equipmentId and b.dateOccured >= a.dateOccured order by b.dateOccured asc ),'01/01/2008') as 'DownDate' from EquipmentUptime a where a.transactionId=200 ) c ) d group by d.equipmentId
I have a table with a primary key, what I really need is something like an IDENTITY, but with the character 'X' and the last to digits of the year added on the front. Is there another way to update the field automatically like an IDENTITY would do, automatically incrementing as fields are inserted.
I apologize for the length of this message, but I think I need to include all this info so that the problem is understood. I am having what appears to be a problem capturing the return code from a failed BCP.
I create a stored proc to use BCP to load a table:
create procedure sp_bcp_load as declare @RC int execute @RC = master..xp_cmdshell "bcp JON..W4KPV in e:inetpubftprootfinreslaw4kpv.g4000.data /Sdbmtss1 /m 0 /f d:mssqluserdatafinresW4KPV.fmt /Usa /P /e d:mssqluserdatafinrescp1.err /t""|"" /r "
select 'Return code from bcp = ', @RC if @RC <> 0 BEGIN print 'BCP Error.' return (8) END GO
If I execute the SP, and encounter a transaction log full error, the return code is still zero:
1000 rows sent to SQL Server. 45000 total 1000 rows sent to SQL Server. 46000 total Msg 1105, Level 17, State 2: Server 'DBMTSS1', Line 1:
Can't allocate space for object 'Syslogs' in database 'Jon' because the 'logsegment' segment is full. If you ran out of space in Syslogs, dump the transaction log. Otherwise, use ALTER DATABASE or sp_extendsegment to increase the size of the segment.
(54 row(s) affected)
----------------------- ----------- Return code from bcp = 0
If I execute the SP again, it correctly returns a non-zero value:
Msg 1105, Level 17, State 2: Server 'DBMTSS1', Line 1: Can't allocate space for object 'Syslogs' in database 'Jon' because the 'logsegment' segment is full. If you ran out of space in Syslogs, dump the transaction log. Otherwise, use ALTER DATABASE or sp_extendsegment to increase the size of the segment.
(6 row(s) affected)
----------------------- ----------- Return code from bcp = 1
(1 row(s) affected)
BCP Error.
Does anybody have an idea why this behaves this way? Any suggestions on how to trap an error on the first call?
I am posting this information simply as an FYI. This is in reference to the MS-SQL command "CONVERT"
I spent over 2 hours :rolleyes: screwing around trying to find out different ways of formatting dates from MS-SQL into something that makes sense for what I needed. I googled everything I could think of and found multiple references that said the info is available on MSDN.. but I could not find it. What I did find were thousands of relatively useless references to "format codes" for converting dates, but with no references to what the different format codes would ultimately yield, or what format codes were available to use.
What I ended up doing was writing a small script to generate a list of all of the variations I could find.
Below is the script, and the output that it yielded. Now, before I get bombarded with "there is a better way" I know there probably is. But this is the way that I needed to do it this particular time. If there are technical errors in my explanation, anyone is welcome to correct them. But after 2 hours of messing with this for what should have been a super simple single .0009 second command, I am just irritated beyond belief that it had to be this complicated to find any useful information on the subject. That is why I am creating this. Hopefully it helps someone else.
The format for the MS SQL CONVERT command is :
CONVERT( length_of_output, date, format_code )
length_of_output : is exactly that . the number of characters that you want returned as your result. If you use a length of 6 you will only see the first 6 characters that are returned. I found the longest valid length to be 28 characters, but I went as high as 128 just for giggles and to see if it revealed any secrets.
date : is a valid date, I used directly the getdate() function
format_code : well.. that's the tricky part. See below.
What I did was ran a script that originally went from 1 to 20,000. It crashed at 15. Apparently the format codes are not totally sequential. So I put in an on error resume next.
What I found is that : 1) the codes are not uninterrupted sequential numbers. 2) the code output repeats every 255 3) negative numbers can be used, but its pointless. 4) useful valid codes are in the ranges of : 0-14, 20-25, 100-114, 120, 121, 126, 130 and 131 5) 0-25 typically represent "short dates" with the year being only 2 digits, but there are exceptions 6) 100 and above always returned a 4 digit year. the exception was 130 and 131, I don't know what it was trying to do.
Here is the script i ran
<% on error resume next
for iintCounter = 0 to 256 SQL = "SELECT CONVERT(CHAR(128), getdate(), " & iintCounter & " ) as TheDate" Set rsTheDateFormat = TheDatabase.Execute(SQL)
I have files with area codes that are several years old. Everything I've seen about updating area codes deals with area codes that are current and are about to split in the near future. How would I go about bringing old area codes up to date?
I am working with a table that has zip codes listed in lengths of 9,8,5 and 4 digits. The table is created this way and I have no way of changing the data outside of SQL. I am trying to get the last four digits off of all the zip codes so that I only have to work with zip codes in lengths of 5 and 4