Adding columns and data to table - sql

I am trying to run the following queries. When I run them separately the code executes correctly. When I run them together I get the error message:
Msg 207, Level 16, State 1, Line 11
Invalid column name 'TotOP'.
Msg 207, Level 16, State 1, Line 12
Invalid column name 'TotPK'.
It's as if the first query has not run at all? - Any ideas
As a work around I know that I can generate all of the columns at the beginning and only partially populate the table leaving these final two columns empty until I run the second query however I am curious to know why these statements can be run separately but not together.
Query 1:
ALTER TABLE [fcgen].[RPD1yeardata]
ADD [TotOP] DECIMAL (7,3) NULL,
[TotPK] DECIMAL (7,3) NULL;
Query 2:
UPDATE [fcgen].[RPD1yeardata]
SET [TotOP] = [1]+[2]+[3]+[4]+[5]+[6]+[7]+[8]+[9]+[10]+[11]+[12]+[13]+[14]+[39]+[40]+[41]+[42]+[43]+[44]+[45]+[46]+[47]+[48],
[TotPK] = [15]+[16]+[17]+[18]+[19]+[20]+[21]+[22]+[23]+[24]+[25]+[26]+[27]+[28]+[29]+[30]+[31]+[32]+[33]+[34]+[35]+[36]+[37]+[38]
FROM [fcgen].[RPD1yeardata]

just use GO after 1s query
ALTER TABLE [fcgen].[RPD1yeardata]
ADD [TotOP] DECIMAL (7,3) NULL,
[TotPK] DECIMAL (7,3) NULL;
Go
--Query 2:
UPDATE [fcgen].[RPD1yeardata]
SET [TotOP] = [1]+[2]+[3]+[4]+[5]+[6]+[7]+[8]+[9]+[10]+[11]+[12]+[13]+[14]+[39]+[40]+[41]+[42]+[43]+[44]+[45]+[46]+[47]+[48],
[TotPK] = [15]+[16]+[17]+[18]+[19]+[20]+[21]+[22]+[23]+[24]+[25]+[26]+[27]+[28]+[29]+[30]+[31]+[32]+[33]+[34]+[35]+[36]+[37]+[38]
FROM [fcgen].[RPD1yeardata];

Related

Msg 8114, Level 16, State 5, Line 31 Error converting data type varchar to bigint

I'm trying to convert a varchar column to bigint and keep getting an error.
I've tried to alter the column using every exact or approximate data types and it will not convert. I've trimmed and cleaned the data and it still has issues.
This is the code that I have been using.
USE [database1]
GO
ALTER TABLE [dbo].[table1]
ALTER COLUMN [column1] bigint
GO
These are the results of the code above
Msg 8114, Level 16, State 5, Line 31
Error converting data type varchar to bigint.
The statement has been terminated.
Any help is appreciated, thank you.
You would appear to have invalid values. So, update them away:
update t
column1 = convert(varchar(255), try_convert(bigint, column1));
Then try changing the column type.
Or, just add a computed column:
alter table t add column1_bi as (try_convert(bigint, column1));
You can see what the bad values are using:
select column1
from t
where try_convert(bigint, column1) is null and column1 is not null;

How to Use the OUTPUT of an Insert Query for another insert query

I'm trying to insert 2 records into 2 tables by using a subquery, but it gives me a syntax error.
Msg 156, Level 15, State 1, Line 4
Incorrect syntax near the keyword 'INSERT'.
Msg 102, Level 15, State 1, Line 4
Incorrect syntax near ')'.
The query that I'm trying to execute is
INSERT INTO [Files] ([FileTransformationId],[FileTypeEnumId])
VALUES
(
(INSERT INTO [FileTransformations] OUTPUT INSERTED.FileTransformationId DEFAULT VALUES),
2
)
Is this possible?
You need to store the output in a variable first. So, I think you want something like this:
DECLARE #variable TABLE (value INT)--change type depending on your need
INSERT INTO [FileTransformations]
OUTPUT INSERTED.FileTransformationId INTO #variable(value)
VALUES(.....)
INSERT INTO [Files] ([FileTransformationId],[FileTypeEnumId])
SELECT value, 2 FROM #variable
See How do I use an INSERT statement's OUTPUT clause to get the identity value? for more info on using output variables and Insert into table from table variable? for then inserting from that table variable.
Another option, if you just want the id of the last inserted record is to use scope_identity(). So you could write the above as:
INSERT INTO [FileTransformations]
VALUES(.....)
INSERT INTO [Files] ([FileTransformationId],[FileTypeEnumId])
VALUES scope_identity(), 2

Setting a varchar column length with a variable or a subquery

I have a table that is created by an import of an Excel file. As is the case, all text fields are imported as nvarchar(255). I'd rather do the bulk import then manipulate the table afterwards. I know SSIS allows me to set data types and sizes via data mapping, but that doesn't seem to work consistently for me. Maybe I'm not holding my mouth right...
Anyway, I want to change the varchar length definitions to the max length of the data in each column. Rather than run a statement to check the max length as a literal...
select max(len(rtrim(FIELD))) from TABLE$
...I want to do it in code. So I hit on this idea:
declare #Var int
set #Var = (select max(len(rtrim(FIELD))) from TABLE$)
alter table dbo.TABLE$ alter column FIELD varchar(#Var)
Lines one and two work fine, but it gives me an error when executing the third line:
Msg 102, Level 15, State 1, Line 5
Incorrect syntax near '#Var'.
So I tried this, thinking it would be a more compact solution...
alter table dbo.TABLE$
alter column FIELD varchar(select max(len(rtrim(FIELD))) from TABLE$)
...but it wasn't. I got these errors:
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'select'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near ')'.
So my question is kind of a two-parter. First, why won't these methods work, and second, what would work--short of finding the mas length of each column, then setting the varchar length with a literal?
Thanks in advance.
Dynamic SQL would work for what you're trying to do. Whether it's the right tool for the job or the right thing to do is another story. Give this a shot:
DECLARE #cmd NVARCHAR(4000)
SET #cmd = 'ALTER TABLE dbo.Table$ ALTER COLUMN FIELD VARCHAR(' + CAST((SELECT MAX(LEN(RTRIM(FIELD))) FROM dbo.TABLE$) AS NVARCHAR(10)) + ')'
EXEC(#cmd)
That query parses but I didn't try to run it. Be careful using Dynamic SQL though. It can get you into trouble if you start using it everywhere. Further reading:
http://sqlmag.com/database-performance-tuning/don-t-fear-dynamic-sql
http://www.sommarskog.se/dynamic_sql.html

Inserting last two digits from column into new column

So I'm supposed to take the last two digits from the phone number, and insert it into a new column in the same table.
I'm currently getting this error:
Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into column 'Pass_id', table 'lunches.dbo.passenger'; column does not allow nulls. INSERT fails.
The statement has been terminated.
This is the query I'm using to get this error:
INSERT INTO dbo.passenger (age)
SELECT
RIGHT(phone, 2)
FROM dbo.passenger
UPDATE dbo.passenger
SET age = Cast(Right(phone, 2) As tinyint)
WHERE phone IS NOT NULL
AND Right(phone, 2) NOT LIKE '%[^0-9]%'

Error when using openrowset for particular record

INSERT INTO OPENROWSET('MSDASQL', 'Driver=PostgreSQL Unicode;uid=postgres;Server=localhost;port=5432;database=data;pwd=xxx',
'select SanctionId,SchemeType,SchemeCode,CorrigendumStatus,AttendumStatus,yearofPlan,ReceivedDate from tesing WHERE SanctionId = ''-1'' ')
select SanctionId,SchemeType,SchemeCode,CorrigendumStatus,AttendumStatus,yearofPlan,ReceivedDate from testing where SanctionId=1103
While executing the above query, I am getting following error:
Msg 8152, Level 16, State 10, Line 1
String or binary data would be truncated.
The statement has been terminated.
Can anyone help me to resolve this?
You will have to check the source data against the target column definitions.
This happens when you try to insert, say, 100 characters into a varchar(50) column