Using cast in insert statement - sql

I am inserting some raw data into a table in MS SQL 2005 from excel.
Some of these data are not formatted correctly ie the amount colum is formatteT as a number 12345 whereas i need to be like 123.45 so i use this
CAST(TRANSACTION_HISTORY.AMOUNT AS decimal) / 100
to convert it correctly.
However is there a way to use the cast in an insert statement??
thanks

You can use CAST in any kind of statement(Insert, update, delete, select) where you use data.
Insert into table1 values( CAST(col1 as nvarchar(50)) )

I assume you're using a linked server or openquery to get the data from excel. You can cast in the select statement.
So
INSERT INTO YourTable
SELECT Cast(Transaction_History.Amount AS Decimal)/100
FROM EXCELLINK...[$Sheet1]
You could also just update all values in the table after you do the import
UPDATE YourTable
SET YourColumn = YourColumn/100

Related

Datatype compatibility: int vs. nvarchar

I am using below sql statement to read and import data from excel spreadsheet to database table:
INSERT INTO [dbo].[TestTable] ([ColumnA], [ColumnB], [ColumnC], [ColumnD])
SELECT A.[AAA], A.[BBB], A.[CCC], A.[DDD] FROM OPENROWSET
('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;Database=C:\Temp\TestFile\01-TestFile.xlsx;HDR=YES', 'select * from [Sheet$]') AS A;
TestTable has four columns, only accepting integer datatypes. The import works well with numbers in the database spreadsheet. However, if for some reason there is a mistake in the file (i.e. there is text instead of digits), it fails and I get an error converting nvarchar to int datatype. Is there any way to ensure the upload still works - that text is ommitted and appears as NULL in the table?
Try TRY_CAST as shown below. Works for SQL Server 2012+.
SELECT TRY_CAST('TEST' AS INT)
See more on TRY_CAST (Transact-SQL)

How to validate/restrict values in a column as per a specific format in a sql Database

I am working on an application that populates values from sql Database in a format two numeric and alpha character e.g 11G,34H. There is no validation or check for the same.I want to put put checkpoint/validation from Database end.Is it possible to implement via SQL procedure or anything.Can anyone help me with the code.
Try the below query
DECLARE #strtable TABLE (column1 VARCHAR(50))
INSERT INTO #strtable
VALUES ('11H'),('sda'),('175HH'),('1H1'),('282')
INSERT INTO YourTable (Column1)
SELECT Column1
FROM #strtable
WHERE LEN(column1)=3
AND ISNUMERIC(LEFT(column1,2))=1
AND ISNUMERIC(RIGHT(column1,1))!=1
--Output : 11H

Error converting varchar to bigint

I got the error where my data type is varchar, then I want to insert value/input in textboxt = 'smh85670s'.
It appear to be error. As far as I know varchar can accept characters and numbers, but why does it keep throwing this error?
If I insert value '123456' the table can accept that value.
Please guide me. What data type should I use?
Assuming that you are using Stored procedures (which have an insert query) or directly firing an insert query into DB, you must be sending all data as parameters like say #param1, #param2,...
Your insert query will be like
INSERT INTO Sometable ( Amount, textbox,... )
SELECT #param1, #param2 ,...
Just add a cast in this query to make it work
INSERT INTO Sometable ( Amount, textbox,... )
SELECT #param1, CAST(#param2 as varchar),...

Filter dates stored as varchar in SQL Server

I am using SQL Server 2008 R2 on the EC2 instance. I have a database having 4 fields of all varchar(50).
SELECT
*
FROM
xyz
WHERE
DataDate ='20140609'
This query gives no result.
SELECT
*
FROM
xyz
WHERE
DataDate = (Select MAX(DataDate) from xyz)
This query runs perfectly.
Select MAX(DataDate) from xyz
This query results in 20140609.
I cannot understand why this this happening. Can someone please explain this?
As stated in comments it's likely due to leading spaces in the values. If you do the following to remove any spaces from the values it should work:
SELECT *
FROM xyz
WHERE REPLACE(DataDate, ' ', '')='20140609'
Alternately, you could use LTRIM / RTRIM functions to do this.
Sample SQL Fiddle
create table SampleData(myDate varchar(50))
insert into SampleData(myDate) values(' 20140609 ')
insert into SampleData(myDate) values('20140608')
insert into SampleData(myDate) values('20140607')
insert into SampleData(myDate) values('20140606')
Both of these queries work in the fiddle:
SELECT *
FROM SampleData
WHERE REPLACE(myDate, ' ', '')='20140609'
Select MAX(REPLACE(myDate, ' ', '')) from SampleData
Future Advice:
Even so, it's not a good idea to save dates as varchar for numerous reasons so I would suggest changing that if possible.
The below would perform a conversion on your existing data to convert them to valid dates, whilst removing any spaces, assuming your dates are always in the format YYYYMMDD:
SELECT cast(REPLACE(DataDate, ' ', '') as DateTime) FormattedDate
FROM xyz
To implement this, you could create a new DateTime column on the table and insert the correct date values in to there with something like below and then modify your code to use the new column:
First add a new column to the table:
ALTER TABLE xyz
ADD FormattedDate DateTime NULL
Then update the data in the new column so it holds the converted dates:
UPDATE xyz
SET FormattedDate = cast(REPLACE(DataDate, ' ', '') as DateTime)
in sql spaces count as the character. Then use like operator to this query as
SELECT
*
FROM
xyz
WHERE
DataDate like '%20140609%'
Can you modify the query as below and give it a go ?
SELECT
*
FROM
xyz
WHERE
DataDate ='2014-06-09'

SQL Command to execute multiple times?

I have situations that I need to write multiple rows of the same value to setup some tables. Say I have to add 120 rows with two columns populated. I am looking for a shortcut, instead of having the Insert line repeated n times. How to do this?
In SQL Server Management Studio, you can use the "GO" keyword with a parameter:
INSERT INTO YourTable(col1, col2, ...., colN)
VALUES(1, 'test', ....., 25)
GO 120
But that works only in Mgmt Studio (it's not a proper T-SQL command - it's a Mgmt Studio command word).
Marc
How about
Insert Table( colsnames )
Select Top 120 #value1, #Value2, etc.
From AnyTableWithMoreThan120Rows
Just make sure the types of the values in the #Value list matches the colNames List
what about
insert into tbl1
(col1,col2)
(select top 120 #value1,#value2 from tbl2)
if in sql server 2008 . new in sql server 2008 to insert into a table multiple rows in a single query .
insert into tbl1
(col1,col2)
values
(#value1,#value2),(#value1,#value2),.....(#value1,#value2)
Put the values in an unused table for safe keeping. From there you can insert from this table to the tables you need to setup.
Create an Excel Spreadsheet with your data.
Import the speadsheet into Sql Server.
You can even try with something like this(just an example)
declare #tbl table(col1 varchar(20),col2 varchar(20))
; with generateRows_cte as
(
select
1 as MyRows
union all
select
MyRows+1
from generateRows_cte
where MyRows < 120
)
insert into #tbl(col1,col2)
select
'col1' + CAST(MyRows as varchar),'col2' + CAST(MyRows as varchar)
from generateRows_cte OPTION (MAXRECURSION 0)
select * from #tbl
Note:- Why not you are trying with Bulk insert into SqlServer from a dataset ? I didnot notice first that u have a front end too(VB)!