Concatinating SmallInt Data Type

Aug 20, 2007

Newbie question regarding a db I have inherited. 
A table FullDocuments has a DocNo column with smallint data type and a SequenceNo column also with smallint data type.
DocNo
has numbers that represent persons.  SequenceNo has numbers that
represent specific documents associated with each person (DocNo).
So DocNo 5 and Sequence 3 represents the 3rd document associated with person 5.
My SELECT statement looks like this:
SELECT ReadingNo, SequenceNo
This returns data like this: 5    3
I would like to concatenate the SELECT statement to return like this: 5-3
So I made Sql like this:
SELECT ReadingNo + '-" + SequenceNo 
Which
returns a alias ('No Column Named') result value of 8 which is an
arithmetic result instead of a string concatination that I want.
So my questions are:
1. 
Should the original database designer have used string data types for
these columns since they will never be used for math purposes?
2. 
Do I need to cast them to string data type (like nchar(4) - since
neither column will ever exceed 4 digits) to get the result I desire?
3.  Or can I keep them as smallint and modify my SELECT statement to allow concatination yielding a string result?

View 4 Replies


ADVERTISEMENT

Index Creation Causes Error The Conversion Of A Char Data Type To A Datetime Data Type Resulted...

Jul 23, 2005

Hi all,I have a table called PTRANS with few columns (see create script below).I have created a view on top that this table VwTransaction (See below)I can now run this query without a problem:select * from dbo.VwTransactionwhereAssetNumber = '101001' andTransactionDate <= '7/1/2003'But when I create an index on the PTRANS table using the command below:CREATE INDEX IDX_PTRANS_CHL# ON PTRANS(CHL#)The same query that ran fine before, fails with the error:Server: Msg 242, Level 16, State 3, Line 1The conversion of a char data type to a datetime data type resulted inan out-of-range datetime value.I can run the same query by commeting out the AssetNumber clause and itworks fine. I can also run the query commenting out the TransactionDatecolumn and it works fine. But when I have both the conditions in theWHERE clause, it gives me this error. Dropping the index solves theproblem.Can anyone tell me why an index would cause a query to fail?Thanks a lot in advance,AmirCREATE TABLE [PTRANS] ([CHL#] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,[CHCENT] [numeric](2, 0) NOT NULL ,[CHYYMM] [numeric](4, 0) NOT NULL ,[CHDAY] [numeric](2, 0) NOT NULL ,[CHTC] [char] (2) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL) ON [PRIMARY]GOCREATE VIEW dbo.vwTransactionsASSELECT CONVERT(datetime, dbo.udf_AddDashes(REPLICATE('0', 2 -LEN(CHCENT)) + CONVERT(varchar, CHCENT) + REPLICATE('0', 4 -LEN(CHYYMM))+ CONVERT(varchar, CHYYMM) + REPLICATE('0', 2 -LEN(CHDAY)) + CONVERT(varchar, CHDAY)), 20) AS TransactionDate,CHL# AS AssetNumber,CHTC AS TransactionCodeFROM dbo.PTRANSWHERE (CHCENT <> 0) AND (CHTC <> 'RA')*** Sent via Developersdex http://www.developersdex.com ***Don't just participate in USENET...get rewarded for it!

View 1 Replies View Related

System.Data.SqlClient.SqlException: The Conversion Of A Char Data Type To A Datetime Data Type Resulted In An Out-of-range Datetime Value.

Dec 14, 2005

After testing out the application i write on the local pc. I deploy it to the webserver to test it out. I get this error.

System.Data.SqlClient.SqlException: The conversion of a char data type to a
datetime data type resulted in an out-of-range datetime value.

Notes: all pages that have this error either has a repeater or datagrid which load data when page loading.

At first I thought the problem is with the date, but then I can see
that some other pages that has datagrid ( that has a date field) work
just fine.

anyone having this problem before?? hopefully you guys can help.

Thanks,

View 4 Replies View Related

Converting A Data Type Double To A Type Float Using A Data Adapter &&amp; SSCE 3.5

Feb 13, 2008

Hi,

I can populate a dataTable with type double (C#) of say '1055.01' however when I save these to the CE3.5 database using a float(CE3.5) I lose the decimal portion. The 'offending' code is:


this.court0TableAdapter1.Update(this.mycourtsDataSet1.Court0);

this.mycourtsDataSet1.AcceptChanges();

this.court0TableAdapter1.Fill(this.mycourtsDataSet1.Court0);


This did not happen with VS2005/CE3.01.

I have tried changing all references to decimal (or money in CE3.5) without luck.

I'm beginning to think that string may be the way to go!!!!!!!

Can someone shed some light on my problem.

Thanks,

Later:

It's necessary to update the datatable adapter as the 3.01 and 3.5 CE are not compatible.

View 4 Replies View Related

COnverting Numeric Data Type (Oracle) To Date Data Type Using SSIS

Mar 7, 2007

We have some columns in a table where the date is stored as 19980101 (YYYYMMDD). The data type for this column is NUMBER(8) in Oracle.

I need to copy rows from Oracle to SQL Server using SSIS. I used the Data Conversion transformation editor to change it to DT_DATE, but the rows are not being inserted to the destination.

On Error, If I fail the component, then the error is :

There was an error with input column "ORDER_DATE_CONV" (1191) on input "OLE DB Destination Input" (29). The column status returned was: "Conversion failed because the data value overflowed the specified type.".

Regards

RH

View 3 Replies View Related

Concatinating With Cursor

May 6, 2008

 frenz:
Can any one send me the code for
concatinating cells values of column in to one cell of that column using cursors.


Ex:

hobbyID

h1

h2

h3

hobbyId
h1,h2,h3

View 1 Replies View Related

Concatinating Columns

Aug 8, 2006

Hello all.

I am taking details from a linked server file (.XLS file). Two of the fields in this file are STARTTIME and STARTDATE.

The problem I have is that these have to be imported into a SQL table, but only into one column of type DATETIME. The column name is STARTDATE. I really have no idea on how to go about this. Any ideas would be greatly appreciated.

Thanks.

View 4 Replies View Related

Concatinating Variables

Jul 20, 2005

Hello,How do I concatinate a variable. Here's the scenarios:declare @var1 varchar(20)declare @var2 varchar(20)declare @var3 varchar(20)declare @var4 varchar(20)....declare @var32 varchar(20)set @var1 = 'Something 1'set @var2 = 'Something 2'....set @var32 = 'Something 3'/* I have to store the values of these individual variables. I wish tohave a "While" routine which iterates through the above variables. Iwish to have the variable name concatinated as that I do not have towrite numerous lines of code setting up individual 32 variables. Howcould I use the '+' operator to join 'var' + @count . Where count isfrom 1 through 32. I am having some trouble with the syntax.*/Regards,VS

View 7 Replies View Related

Concatinating Select Results

Jan 18, 2006

Hey everyone,

I have an SSIS conversion issue. I'm pulling two tables from a DB2 database into SQL 2005. One table has a list of work orders, and the other has a list of work order comments. There is a unique identifier between the two tables so that a join can be used, however, due to size limitations, I need to be able to combine both tables.

The end result will be replicated out for SQL Mobile Edition and the file is too large when both tables exist so I am wanting to concatinate all the comments for each work order into a single text field in the work orders table.

Here is what I am wanting to accomplish:

UPDATE tblWorkOrdersSET Comments = (SELECT Comments
FROM tblComments
WHERE tblWorkOrders.ReqNum =
tblComments.ReqNum)

I know that this statement will not work because there is a one-to-many relationship between the tables so each work order could get multiple results.

I would appreciate any suggestions.

Thanks,

Lee.

View 2 Replies View Related

The Conversion Of A Char Data Type To A Datetime Data Type!!

May 13, 2008

hello all .. I have a form that includes two textboxes (Date and Version) .. When I try to insert the record I get the following error message .. seems that something wrong with my coversion (Data type)"The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.The statement has been terminated."
 
in my SQL database I have the date feild as datetime and the version as nvarchar(max)
this is the code in the vb page .. Can you please tell me how to solve this problem?Imports System.Data.SqlClient
Imports system.web.configuration

Partial Class Admin_emag_insert
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Record_DateTextBox.Text = DateTime.Now

End Sub

Protected Sub clearButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles clearButton.Click
Me.VersionTextBox.Text = ""
End Sub

Protected Sub addButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles addButton.Click
Dim objConnection As SqlConnection
Dim objDataCommand As SqlCommand
Dim ConnectionString As String
Dim record_date As Date
Dim version As String
Dim emagSQL As String

'save form values in variables
record_date = Record_DateTextBox.Text
version = VersionTextBox.Text

ConnectionString = WebConfigurationManager.ConnectionStrings("HRDBConnectionString").ConnectionString

'Create and open the connection
objConnection = New SqlConnection(ConnectionString)
objConnection.Open()
emagSQL = "Insert into E_Magazine (Record_Date, Version ) " & _
"values('" & record_date & "','" & version & "')"

'Create and execute the command
objDataCommand = New SqlCommand(emagSQL, objConnection)
objDataCommand.ExecuteNonQuery()
objConnection.Close()

AddMessage.Text = "A new emagazine was added successfully"

Me.VersionTextBox.Text = ""

End Sub
End Class
 

View 10 Replies View Related

Converting Numeric Data Type To Text Data Type

Jul 20, 2005

Hi,I would like to convert a dollar amount ($1,500) to represent Fifteenhundred dollars and 00/100 cents only for SQL reporting purposes. Isthis possible and can I incorporate the statement into an existingleft outer join query.Thanks in advance,Gavin

View 1 Replies View Related

Changing User Defined Data Type's Data Type

Sep 12, 2006

Hi,



I have a user defined data type which is called DEmployeeName,

it's length is varchar(20), how do i change it into varchar(30) without droping it?

I'm using SQL server 2005.

Thanks in advance..

View 1 Replies View Related

Convert Text Data Type To Smalldatetime Data Type

Oct 9, 2007

I have a field that is currently stored as the data type nvarchar(10), and all of the data in this field is in the format mm/dd/yyyy or NULL. I want to convert this field to the smalldatetime data type. Is this possible?
I've tried to use cast in the following way, (rsbirthday is the field name, panelists is the table), but to no avail.


SELECT rsbirthday CAST(rsbirthday AS smalldatetime)

FROM panelists


the error returned is "incorrect syntax near 'rsbirthday'.

I'm rather new to all things SQL, so I only have the vaguest idea of what I'm actually doing.

Thanks for the help!

View 10 Replies View Related

Concatinating Two Field And Insert The Result

Aug 20, 2005

Hii,I need to concatinate two field and insert the result into each record. So far I managed to display the concatination but how do I insert it?use northwind
select city, region,([city]+ +[region]) as uniqefrom customerswhere region is not nullThe resulting records in Quary Anchorage AK AnchorageAKTsawassen BC TsawassenBCVancouver BC VancouverBCSan Francisco CA San FranciscoCA
 

View 1 Replies View Related

SmallInt

Aug 3, 2004

In vb.net what kind of data can I inject in a smallInt lenght 2 Data Type? Right now I am trying to pass an integer to my SP and it gives me the error "Error converting data type nvarchar to smallint" So I guess that I am not passing the right type of data or I have to cast it?
Thanks

cmdSelect.Parameters.Add("@CustomerId", "iCustomerId")

View 3 Replies View Related

Getting Error : : The Conversion Of A Char Data Type To A Datetime Data Type Resulted In An Out-of-range Datetime Value

Jan 28, 2008

update tblPact_2008_0307 set student_dob = '30/01/1996' where student_rcnumber = 1830when entering update date in format such as ddmmyyyyi know the sql query date format entered should be in mmddyyyy formatis there any way to change the date format entered to ddmmyyyy in sql query?

View 5 Replies View Related

Problem In Concatinating Two Paramters To Update One Column

Sep 20, 2007

 Using gridview to display the data and sql server 2000 I have
a column in the database say departtime of datetime datatype that
cntains the date and time resp(09/19/2007 9:00 PM). I am separating the
date and time parts to display in two different textboxes say
txt1(09/19/2007) contaons date and txt2(9:00 PM) contains time by using
the convert in sqldatasource. Now i need to update the column in the
database and i am using Updatecommand with parameters in aspx  lke
updatecommand = "Update table set departtime = @departtime" . How  can
i  update my column as datetime by getting the data from 2 texboxes as
now i have 2 textboxes displaying data for single column means if user
edit the data in txt1 as(10/19/2007) then on click of update i need to
populate the column daparttime as (10/19/2007 9:00 PM).Please let me know if you have any questions.

View 1 Replies View Related

Concatinating String Values From Multiple Rows

Nov 4, 2006

I currently have some SQL code that is used to build a string that is a concatination of string values across multiple rows.  The subqueries in the script sometimes return NULL values so I use the following statement to change the default behavior of the concatination operator which prevents my query from returning NULL:

SET CONCAT_NULL_YIELDS_NULL ON

Here's the code snippet:

select DISTINCT

(SELECT CASE WHEN (t1.MaskValue & HDR.TranTypeID)=1 THEN ' ' + t1.description ELSE '' END FROM transactiontypes t1 WHERE (t1.MaskValue & HDR.TranTypeID)=1) +

(SELECT CASE WHEN (t2.MaskValue & HDR.TranTypeID)=2 THEN ' ' + t2.description ELSE '' END FROM transactiontypes t2 WHERE (t2.MaskValue & HDR.TranTypeID)=2) +

(SELECT CASE WHEN (t3.MaskValue & HDR.TranTypeID)=4 THEN ' ' + t3.description ELSE '' END FROM transactiontypes t3 WHERE (t3.MaskValue & HDR.TranTypeID)=4) +

(SELECT CASE WHEN (t4.MaskValue & HDR.TranTypeID)=8 THEN ' ' + t4.description ELSE '' END FROM transactiontypes t4 WHERE (t4.MaskValue & HDR.TranTypeID)=8) +

(SELECT CASE WHEN (t5.MaskValue & HDR.TranTypeID)=16 THEN ' ' + t5.description ELSE '' END FROM transactiontypes t5 WHERE (t5.MaskValue & HDR.TranTypeID)=16)) as 'Transaction Type'

FROM HDResponse HDR

Here's the underlying table structure:
CREATE TABLE [dbo].[TransactionTypes](
             [ID] [int] IDENTITY(1,1) NOT NULL,
             [Description] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,        [MaskValue] [int] NOT NULL) ON [PRIMARY]
CREATE TABLE [dbo].[HDResponse](
             [ResponseID] [int] IDENTITY(1,1) NOT NULL,
             [LoggedDateTime] [datetime] NULL,
             [ResponseTypeTripID] [int] NULL,
             [ResponseTypeID] [int] NULL,
             [ResponseTypeObjectID] [int] NULL,
             [ObjectID] [int] NULL,
             [IDHolderID] [int] NULL,
             [TransportCode] [int] NULL,
             [CardID] [int] NULL,
             [IssueCode] [smallint] NULL,
             [EventDateTime] [datetime] NULL,
             [Response] [bit] NULL,
             [TranTypeID] [int] NULL)
             ON [PRIMARY]

The problem I am having is I need to be able to use the query above in a view used for reporting.  Unfortunately, you cannot use SET CONCAT_NULL_YIELDS_NULL ON in a view.  This causes my query to return NULL if any of the subqueries return NULL.  I could create a function to do something similar and reference the function in the query but I can't help but think there must be a way to get this done in a single query.

Any thoughts or ideas would be greatly appreciated.

Thanks!!!!!

View 1 Replies View Related

Smallint To Datetime

Feb 15, 2006

I have a dbfield which holds a smallint value for the time eg. 1406 . I have to add this value to a datetime value in another field but need the result as a datetime value.
The result would be time(int) + date(datetime) = datetime(datetime).
I need this to compare the hours between delivery and dispatch.
Thanks for your help
P

View 7 Replies View Related

DATEDIFF With Smallint

Dec 13, 2007

Hi,

I get smthing I did not expected from the following query.





Code Block
SELECT DATEDIFF(month, datediff( month , LoanApplication.DecidedOnCU,GETDATE()), LoanApplication.Term)
FROM LoanApplication






data type of LoanApplication.Term field is smallint

Values are like 60,20,48 etc.

data type of LoanApplication.DecidedOnCU is date time.

Is it a problem? If so How can I fix this ?


Final answer I want to get from this query is remaining months. Ex: 14, 20 etc.

Thanks

View 5 Replies View Related

Sqlbulkcopy Error : The Given Value Of Type SqlDecimal From The Data Source Cannot Be Converted To Type Decimal Of The Specified

Apr 16, 2008

Hi,

The table in SQL has column Availability Decimal (8,8)

Code in c# using sqlbulkcopy trying to insert values like 0.0000, 0.9999, 29.999 into the field Availability
we tried the datatype float , but it is converting values to scientific expressions€¦(eg: 8E-05) and the values displayed in reports are scientifc expressions which is not expected
we need to store values as is


Error:
base {System.SystemException} = {"The given value of type SqlDecimal from the data source cannot be converted to type decimal of the specified target column."}

"System.InvalidOperationException: The given value of type SqlDecimal from the data source cannot be converted to type decimal of the specified target column. ---> System.InvalidOperationException: The given value of type SqlDecimal from the data source cannot be converted to type decimal of the specified target column. ---> System.ArgumentException: Parameter value '1.0000' is out of range.
--- End of inner exception stack trace ---
at System.Data.SqlClient.SqlBulkCopy.ConvertValue(Object value, _SqlMetaData metadata)
--- End of inner exception stack trace ---
at System.Data.SqlClient.SqlBulkCopy.ConvertValue(Object value, _SqlMetaData metadata)
at System.Data.SqlClient.SqlBulkCopy.WriteToServerInternal()
at System.Data.SqlClient.SqlBulkCopy.WriteRowSourceToServer(Int32 columnCount)
at System.Data.SqlClient.SqlBulkCopy.WriteToServer(DataTable table, DataRowState rowState)
at System.Data.SqlClient.SqlBulkCopy.WriteToServer(DataTable table)
at MS.Internal.MS
COM.AggregateRealTimeDataToSQL.SqlHelper.InsertDataIntoAppServerAvailPerMinute(String data, String appName, Int32 dateID, Int32 timeID) in C:\VSTS\MXPS Shared Services\RealTimeMonitoring\AggregateRealTimeDataToSQL\SQLHelper.cs:line 269"


Code in C#

SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnection, SqlBulkCopyOptions.Default);
DataRow dr;
DataTable dt = new DataTable();
DataColumn dc;

try
{

dc = dt.Columns.Add("Availability", typeof(decimal));
€¦.

dr["Availability"] = Convert.ToDecimal(s[2]); ------ I tried SqlDecimal
€¦€¦€¦.

}
bulkCopy.DestinationTableName = "dbo.[Tbl_Fact_App_Server_AvailPerMinute]";
bulkCopy.WriteToServer(dt);



thx



View 8 Replies View Related

Bulk Insert Task Failing On Data Type Conversion For A Destination Column Of Type Bit

Jul 6, 2006

I am trying to use the Bulk Insert Task to load from a csv file. My final column is a bit that is nullable. My file is an ID column that is int, a date column that is mm/dd/yyy, then 20 columns that are real, and a final column that is bit. I've tried various combinations of codepage and datafiletype on my task component. When I have RAW with Char, I get the error included below. If I change to RAW/Native or codepage 1252, I don't have an issue with the bit; however, errors start generating on the ID and date columns.

I have tried various data type settings on my flat file connection, too. I have tried DT_BOOL and the integer datatypes. Nothing seems to work.

I hope someone can help me work through this.

Thanks in advance,

SK



SSIS package "Package3.dtsx" starting.

Error: 0xC002F304 at Bulk Insert Task, Bulk Insert Task: An error occurred with the following error message: "Cannot fetch a row from OLE DB provider "BULK" for linked server "(null)".The OLE DB provider "BULK" for linked server "(null)" reported an error. The provider did not give any information about the error.The bulk load failed. The column is too long in the data file for row 1, column 24. Verify that the field terminator and row terminator are specified correctly.Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 23 (cancelled).".

Error: 0xC002F304 at Bulk Insert Task 1, Bulk Insert Task: An error occurred with the following error message: "Cannot fetch a row from OLE DB provider "BULK" for linked server "(null)".The OLE DB provider "BULK" for linked server "(null)" reported an error. The provider did not give any information about the error.The bulk load failed. The column is too long in the data file for row 1, column 24. Verify that the field terminator and row terminator are specified correctly.Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 23 (cancelled).".

Task failed: Bulk Insert Task 1

Task failed: Bulk Insert Task

Warning: 0x80019002 at Package3: The Execution method succeeded, but the number of errors raised (2) reached the maximum allowed (1); resulting in failure. This occurs when the number of errors reaches the number specified in MaximumErrorCount. Change the MaximumErrorCount or fix the errors.

SSIS package "Package3.dtsx" finished: Failure.

View 5 Replies View Related

The Conversion Of A Char Data Type To A Datetime Data Type Resulted In An Out-of-range Datetime Value.

Apr 19, 2008

Advance thanks ....... My table is  TimeSheet:-----------------------------------  CREATE TABLE [dbo].[TimeSheet](    [autoid] [int] IDENTITY(1,1) NOT NULL,    [UserId] [int] NOT NULL,    [starttime] [datetime] NOT NULL,    [endtime] [datetime] NOT NULL,    [summary] [nvarchar](50) NOT NULL,    [description] [nvarchar](50) NULL,    [dtOfEntry] [datetime] NOT NULL,    [Cancelled] [bit] NULL) ON [PRIMARY] My Query is------------------ insert into timesheet (UserId, StartTime,EndTime, Summary, Description,DtOfEntry) values (2, '19/04/2008 2:05:06 PM', '19/04/2008 2:05:06 PM', '66', '6666','19/04/2008 2:05:06 PM')i m not able to insert value Error Message is-------------------------Msg 242, Level 16, State 3, Line 1The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.The statement has been terminated. can any body give any solution  

View 5 Replies View Related

The Conversion Of A Char Data Type To A Datetime Data Type Resulted In An Out-of-range Datetime Value.

Aug 3, 2005

Hey, I have a big problem that i wanna search data from SQL by DateTime like thatselect * from test where recorddate='MyVariableWhichHoldDate'i use variable that holds Date info.i searched a lot infomation on net but there is no perfect solution. i know why this occur but there is no function to solve this problem. i used a lot of ways. it accept yyyy-mm-dd format but my variable format is dd-mm-yyyyy . is there any function for this problem? and any other solution.thanks for ur attentionregards

View 6 Replies View Related

The Conversion Of Char Data Type To Smalldatetime Data Type Resulted In An Out-of-range Smalldatetime Value

Mar 30, 2007

I am using Visual Studio 2005 and SQL Express 2005. The database was converted from MS Access 2003 to SQL Express by using the upsize wizard.



I would like to store the current date & time in a column in a table. This column is a smalldatetime column called 'lastlogin'.

The code I'm using is:



Dim sqlcommand As New SqlCommand _

("UPDATE tableXYZ SET Loggedin = 'True', LastLogin = GetDate() WHERE employeeID = '" & intEmployeeID.ToString & "'", conn)



Try

conn.Open()

sqlcommand.ExecuteNonQuery()

conn.Close()

Catch ex As Exception

MessageBox.Show(ex.Message)

End Try



This code works fine on my local machine and local SQL server. However at the client side this code results in the error as mentioned in the subject of this thread. I first used 'datetime.now' instead of 'getdate()', but that caused the same error. Then I changed the code to 'getdate()', but the error still remains.



The server at the client is running Windows Server 2000 UK . My local machiine is running WIndows XP Dutch.

Maybe the conversion from Dutch to UK has something to do with it. But this should be solved by using the 'Getdate()' function..... ?













View 1 Replies View Related

Converting A Smallint To An Nvarchar

Jul 20, 2005

For a SQL statement in an Alias column I am am combing severalcolumns.But I am having problems with one column as it is a smallint.I get this errorSyntax error converting the nvarchar value to a column of data typesmallintMy Sql statement "Select Stilngcol1 + stringcol2 + intcol1 + stringcol3 As NewColNamefrom Table1I was wondering is there anyway to format/convert the smallint tonvarchar, without changing the database.

View 3 Replies View Related

Connection Type Limitations When Using XML Data Type In SQL Task

Jul 23, 2007

I'm trying to use the SSIS Execute SQL Task to pull XML from a SQL 2005 database table. The SQL is of the following form:




SELECT
(



SELECT
MT.MessageId 'MessageId',
MT.MessageType 'MessageType',
FROM MessageTable MT
ORDER BY MT.messageid desc
FOR XML PATH('MessageStatus'), TYPE


)
FOR XML PATH('Report'), TYPE

For some reason I can only get this query to work if I use an ADO.NET connection type. If I try to use something like the OLEDB connection I get the following error:



<ROOT><?MSSQLError HResult="0x80004005" Source="Microsoft XML Extensions to SQL Server" Description="No description provided"?></ROOT>



Can anyone tell me why the SELECT ... FOR XML PATH... seems only to work with ADO.NET connections?



Thanks

Walter

View 1 Replies View Related

Smallint Vs Int Join With Stats - Suprizing!

Feb 19, 2004

Is an index based on a smallint (16 bit) really faster than an index based on an int (32 bit)
If so, how much...

Four tables

Table A: ID smallint (PK)
Text varchar(50)

Table B:ForeginID smallint (indexed - non unique)
Text varchar(50)
rowID int (PK)

Table C: ID int (PK)
Text varchar(50)

Table D:ForeginID int (indexed - non unique)
Text varchar(50)
rowID int (PK)


Table A and C contain identical data
Table B and D contain identical data
(Tables A and B were filled and then copied to Tables C and D)

Tables A/C are loaded with 64,000 records (-32,000 to 32,000)
Tables B/D are loaded with 6,400,000 records ForeginID loaded randomly with values between -32,000 and 32,000


The purpose of this test is to find out if identical queries joined on a smallint are actually faster than int based.

I ran 3 queries on each set:
- Full select
- Select on ID/Foregin ID
- Select on Table2 RowID joined to table 1


Here are the queries:

#1. Full select (smallint) - grouped to limit result set
-----------------------------------------------------------
SELECT intAID, COUNT(intBID)
FROM TESTintA
INNER JOIN TESTintB ON intAID = intBID
GROUP BY intAID
ORDER BY COUNT(intBID) desc

#2. Select on ID/Foregin ID (smallint)
------------------------------------------
SELECT intAID, intBID, strATXT, strBTXT
FROM TESTintA
INNER JOIN TESTintB ON intAID = intBID
WHERE intAID = 29120


#3. Select on Table2 RowID joined to table 1 (smallint)
------------------------------------------
SELECT intAID, intBID, strATXT, strBTXT
FROM TESTintA
INNER JOIN TESTintB ON intAID = intBID
WHERE intPK = 1050


#4. Full select (int) - grouped to limit result set
------------------------------------------
SELECT lngCID, COUNT(lngDID)
FROM TESTlngC
INNER JOIN TEXTlngD ON lngCID = lngDID
GROUP BY lngCID
ORDER BY COUNT(lngDID) desc


#5. Select on ID/Foregin ID (int)
------------------------------------------
SELECT lngCID, lngDID, strTXTC, strTXTD
FROM TESTlngC
INNER JOIN TEXTlngD ON lngCID = lngDID
WHERE lngCID = 29120

#6. Select on Table2 RowID joined to table 1 (int)
------------------------------------------
SELECT lngCID, lngDID, strTXTC, strTXTD
FROM TESTlngC
INNER JOIN TEXTlngD
ON lngCID = lngDID
WHERE intPK = 1050



Here are the results: (run multiple times to verify)

#1. Full select (smallint) - grouped to limit result set
-----------------------------------------------------------
(8 seconds) - before computing statistics on table
(13 seconds) - after computing statistics on table


#2. Select on ID/Foregin ID (smallint)
------------------------------------------
(0 seconds)


#3. Select on Table2 RowID joined to table 1 (smallint)
------------------------------------------
(0 seconds)


#4. Full select (int) - grouped to limit result set
------------------------------------------
(8 seconds) - before computing statistics on table
(7 seconds) - after computing statistics on table

#5. Select on ID/Foregin ID (int)
------------------------------------------
(0 seconds)


#6. Select on Table2 RowID joined to table 1 (int)
------------------------------------------
(0 seconds)


Conclusion: Not only is there a negligible difference in select performance, generating stats on the smallint actually makes it slower.
(perhaps there is some kind of conversion going on here behind the scenes?)

View 3 Replies View Related

Validate INT, SMALLINT, TINYINT & DECIMAL

Jan 10, 2008

Hi all,

I found a UDF on the web to validate INT data contained in a VARCHAR field:

http://blog.sqlauthority.com/2007/08/11/sql-server-udf-validate-integer-function/

I modified it to accept NULL values and conform more closely to INT specification. Here is my modified function:


CREATE FUNCTION [dbo].[udfIsValidINT]
(
@Number VARCHAR(100)
)
RETURNS BIT
BEGIN
DECLARE @Ret BIT, @ShiftByOne INT;
IF LEFT(@Number, 1) = '-'
SELECT @Number = SUBSTRING(@Number, 2, LEN(@Number)), @ShiftByOne=1;
SELECT @Number = COALESCE(@Number,'0'), @ShiftByOne = COALESCE(@ShiftByOne,0)
IF (PATINDEX('%[^0-9-]%', @Number) = 0
AND CHARINDEX('-', @Number) <= 1
AND @Number NOT IN ('.', '-', '+', '^')
AND LEN(@Number)>0
AND LEN(@Number)<11
AND @Number NOT LIKE '%-%')
SELECT @Ret = CASE WHEN CONVERT(BIGINT,@Number) - @ShiftByOne <= 2147483647
THEN 1 ELSE 0 END
ELSE
SET @Ret = 0
RETURN @Ret
END
GO
SELECT dbo.udfIsValidINT('2147483648')
SELECT dbo.udfIsValidINT('2147483647')
SELECT dbo.udfIsValidINT('-200')
SELECT dbo.udfIsValidINT('-2147483649')
SELECT dbo.udfIsValidINT('32900')
SELECT dbo.udfIsValidINT('1.79E+308')
GO


I also have a separate function for SMALLINT:

CREATE FUNCTION [dbo].[udfIsValidSMALLINT]
(
@Number VARCHAR(100)
)
RETURNS BIT
BEGIN
DECLARE @Ret BIT, @ShiftByOne INT;
IF LEFT(@Number, 1) = '-'
SELECT @Number = SUBSTRING(@Number, 2, LEN(@Number)), @ShiftByOne=1;
SELECT @Number = COALESCE(@Number,'0'), @ShiftByOne = COALESCE(@ShiftByOne,0)
IF (PATINDEX('%[^0-9-]%', @Number) = 0
AND CHARINDEX('-', @Number) <= 1
AND @Number NOT IN ('.', '-', '+', '^')
AND LEN(@Number)>0
AND LEN(@Number)<6
AND @Number NOT LIKE '%-%')
SELECT @Ret = CASE WHEN CONVERT(INT,@Number) - @ShiftByOne <= 32677 THEN 1 ELSE 0 END
ELSE
SET @Ret = 0
RETURN @Ret
END
GO
SELECT dbo.udfIsValidSMALLINT('589')
SELECT dbo.udfIsValidSMALLINT('-200')
SELECT dbo.udfIsValidSMALLINT('-32900')
SELECT dbo.udfIsValidSMALLINT('32900')
SELECT dbo.udfIsValidSMALLINT('1.79E+308')


and one for TINYINT:


CREATE FUNCTION [dbo].[udfIsValidTINYINT]
(
@Number VARCHAR(100)
)
RETURNS BIT
BEGIN
DECLARE @Ret BIT, @L TINYINT;
SET @L = LEN(@Number);
SET @Number = COALESCE(@Number,'0');
IF (PATINDEX('%[^0-9]%', @Number) = 0
AND @L>0
AND @L<4)
SELECT @Ret = CASE WHEN CONVERT(SMALLINT,@Number) < 256 THEN 1 ELSE 0 END
ELSE
SET @Ret = 0
RETURN @Ret
END
GO
SELECT dbo.udfIsValidTINYINT('256')
SELECT dbo.udfIsValidTINYINT('-1')
SELECT dbo.udfIsValidTINYINT('0')
SELECT dbo.udfIsValidTINYINT('255')
SELECT dbo.udfIsValidTINYINT('1.79E+308')


And, finally, a separate function for DECIMAL validation:

CREATE FUNCTION [dbo].[udfIsValidDECIMAL]
(
@Number VARCHAR(100),
@Scale TINYINT,
@Precision TINYINT
)
RETURNS BIT
BEGIN
DECLARE @Ret BIT, @L TINYINT, @DSI TINYINT;
SET @Number = COALESCE(@Number,'0');
IF LEFT(@Number, 1) = '-'
SELECT@Number = SUBSTRING(@Number, 2, LEN(@Number));
SET @L = LEN(@Number);
SET @DSI = @L - LEN(REPLACE(@Number,'.',''))
IF(
PATINDEX('%[^0-9.]%', @Number) = 0
ANDCHARINDEX('-', @Number) = 0
AND@DSI <= 1
AND@L>0
AND@L<=@Scale+@DSI+ CASE @DSI WHEN 1 THEN @L-CHARINDEX('.', @Number) ELSE 0 END
AND @Scale - @Precision >= CASE @DSI WHEN 1 THEN CHARINDEX('.', @Number) - 1 ELSE @L END
)
SELECT @Ret = 1
ELSE
SET @Ret = 0
RETURN @Ret
END
GO
SELECT dbo.udfIsValidDECIMAL('256',2,0)
SELECT dbo.udfIsValidDECIMAL('-1',1,0)
SELECT dbo.udfIsValidDECIMAL('10.123456789123456789',18,17)
SELECT dbo.udfIsValidDECIMAL('10.123456789123456789',18,16)
SELECT dbo.udfIsValidDECIMAL('-255.0000000000000001',3,0)
SELECT dbo.udfIsValidDECIMAL('1.79E+308',9,2)


Node that the DECIMAL validation function specifically tests whether the input number can legally convert to a given decimal scale and precision. Converting a value of 0.234234 over to DECIMAL(1,0) will work, but SQL will truncate the actual decimals to fit it in that space. However, it will throw an error if you have too many whole digits.

On the whole, I was rather rushed to get these created, so there may be some errors I didn't notice. I'm interested in any improvements you guys can make to improve performance or make them cleaner.

Thanks for looking!

- Shane

View 2 Replies View Related

Inserting Time In Smallint Field

Mar 14, 2008

I need to insert rows into a table which contains a smallint field
for time. The times are stored in that colum as integers (898,
11345, 1259, etc.) How can I enter a time like 9:15 AM into this field? I know how to display integer data in hh:mm format but I'm stumped on how I can do the reverse.

Thanks for any help offered.

View 12 Replies View Related

SMALLINT: VALUE: 12 OR 12000 WHAT WILL THE ACTUAL SIZE: 2 BYTES OR ?

Aug 28, 2007

Sql Server has many data types.
For Example:
smallint
Integer data from -2^15 (-32,768) through 2^15 - 1 (32,767). Storage size is 2 bytes.
I want to know that
If it contains like 0 or 100 or 1000 or -200 or -2000  or more or less.
What will its actual size?
2 bytes or change with the value.
Please also mention the reference with your answer. if available.

View 3 Replies View Related

Casting Or Converting Smallint Datatype To Datetime

Sep 8, 2007

A SQL Server 2005 db has three date related-columns (MonthGiven,
DayGiven, YearGiven) each as smallint datatype.  I would like to
create a DocDate column (datetime datatype) that combines the data from
the three existing date-related columns.  I have tried casting and
simple concatentation without success.  ALTER TABLE Details ADD DocDate DateTime NULL

UPDATE Details SET DocDate = CAST(MonthGiven AS DateTime)+ '/' + CAST(DayGiven AS DateTime) + "/" Cast(YearGiven As DateTime)
I think I need to be doing a Conversion instead of casting but
have been unable to implement info I have found in the SQL Server
Developer Center in my situation.

View 11 Replies View Related

Changing Datatype: Smallint To Int In A Large Table..

Jul 13, 2004

Hi,

I need to change the datatype of a very large table from smallint to int...
What would be an ideal solution to get this done in least amount of time. May be I can try with ALTER but , I am not sure about the time it would take ...and the page splits etc..

pls help on the same!!

Thanks
Cheriyan.

View 14 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved