SQL Server 2008 Alter Table Concatenate - sql

I need to concatenate 2 ints and a varchar column into plan_no so it would look like this
Any help would be much appreciated.

We can try using CONVERT here to convert the numeric fields into text:
SELECT
CONVERT(varchar(10), lot) + '-' + forester + '-' +
CONVERT(varchar(10), year) AS plan_no
FROM yourTable;
If you want an update, then just use:
UPDATE yourTable
SET plan_no = CONVERT(varchar(10), lot) + '-' + forester + '-' +
CONVERT(varchar(10), year);

You need to do conversions :
select *, cast(lot as varchar(255)) + '-' +forester + '-' +cast([year] as varchar(5)) as plan_no
from table t;
You can alter your DDL :
alter table t
add plan_no as (cast(lot as varchar(255)) + '-' +forester + '-' +cast([year] as varchar(5)))
Edit :
update t
set plan_no = cast(lot as varchar(255)) + '-' +forester + '-' +cast([year] as varchar(5))
where plan_no is null;

I think you want to update data in your current table:
UPDATE TableName
SET plan_no = cast(lot as nvarchar(50)) + '-' + forester + '-' + cast([year] as nvarchar(50))
Please note: if lot, forester or year columns can contain nulls then you need to wrap values by ISNULL() function

Related

SQL Server : generate a different value for each output row

I am running a query in which I need the SCORE to have a different output for each row. I am able to do it per execution but I have had no luck with RAND as I get a convert from varchar to int error. I need variable number per execution within a range with no decimals. Is there anyway to do this? Any help is appreciated.
SELECT
'Row_Number^FEED_date^database_id^station_id^Form_Type^FBCS_CLAIM_ID^FBCS_LINE_ID^Pay^SCORE^score_date^reason_code^reason_description'
UNION ALL
SELECT
CAST(ROW_NUMBER() OVER ( ORDER BY ( SELECT 1 ) ) AS VARCHAR(20)) + '^' +
CONVERT(VARCHAR, getdate(), 112)+ '^' +
'FBCSTrans'+ '^' + ---took off the 1 so if problems put it back
stationnumber+ '^' +
case when claimtype = 0 then 'HCFA 1500' else 'UB 1450' end+ '^' +
CAST(Claims.claimid AS VARCHAR(50)) + '^' +
CAST(LineID AS VARCHAR(50)) + '^' +
'Y'+ '^' +
**RAND() * 100000 AS random_number** + '^' +
CONVERT(VARCHAR, getdate(), 112)+ '^' +
'' + '^' + ''
FROM
Claims
JOIN
ClaimLines ON Claims.Claimid = Claimlines.Claimid
JOIN
Facilities ON Claims.FacilityID = Facilities.FacilityID
WHERE
Claims.ClaimId IN (SELECT TOP(100000) ClaimId
FROM CLAIMS
WHERE Claims.RecordStatus = 55 AND facilityid = 40)
USE [DATABASE NAME]
SELECT 'Row_Number^FEED_date^database_id^station_id^Form_Type^FBCS_CLAIM_ID^FBCS_LINE_ID^Pay^SCORE^score_date^reason_code^reason_description'
UNION ALL
SELECT
CAST(ROW_NUMBER() OVER ( ORDER BY ( SELECT 1 ) ) AS VARCHAR(20)) + '^' +
CONVERT(VARCHAR, getdate(), 112)+ '^' +
'DATABASE NAME'+ '^' + ---took off the 1 so if problems put it back
stationnumber+ '^' +
case when claimtype = 0 then 'HCFA 1500' else 'UB 1450' end+ '^' +
CAST(Claims.claimid AS VARCHAR(50)) + '^' +
CAST(LineID AS VARCHAR(50)) + '^' +
'Y'+ '^' +
CAST (FLOOR(RAND(CHECKSUM(NEWID()))*(1000-0+1)+100) As NVARCHAR) + '^' +
CONVERT(VARCHAR, getdate(), 112)+ '^' +
'' + '^' + ''
FROM Claims
JOIN ClaimLines on Claims.Claimid = Claimlines.Claimid
JOIN Facilities ON Claims.FacilityID = Facilities.FacilityID
WHERE Claims.ClaimId IN (SELECT TOP(100000)ClaimId FROM CLAIMS WHERE Claims.RecordStatus = 55 and facilityid=40)

concat column names with string inside a string

I am trying to create a pretty column to display but I cannot get a space or hyphen to work. I want the column to display like
Jun-2014 or Jun 2014 but I get errors when I try to insert it the normal way due to the query already being inside a string.
Here is the part I am having trouble with:
(LEFT(DATENAME(month, leadtime),3) + " " + CONVERT(varchar, DATEPART(year, leadtime))) as leadmonth
And here is the rest of the query for context:
set #query = 'SELECT name AS "Lead Source",' + #cols + '
from
(
SELECT d.name, COUNT(u.lead_source_id) AS totalLeads, + "["+ (LEFT(DATENAME(month, leadtime),3) + " " + CONVERT(varchar, DATEPART(year, leadtime)))+"] as leadmonth" +
FROM DI_TrackingDB.dbo.userleads u
INNER JOIN GSPremiumServices.dbo.supplier_product_lead_source_def d ON d.lead_source_id = u.lead_source_id
WHERE vend_id = 355135
AND u.lead_source_id IS NOT NULL
GROUP BY u.lead_source_id, d.name, DATENAME(month, leadtime), DATEPART(year, leadtime), Convert(varchar(7), leadtime, 126)
) x
pivot
(
max(totalLeads)
for leadmonth in (' + #cols + ')
) p '
Please keep in mind I am setting #query so I am already inside of a string.
Any suggestions are appreciated.
The answer was quite simple. Not sure if people didn't quite understand my initial question but the answer was to use two ' on either side of the inner string. Below is the final version of the code that works.
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
SELECT #cols = STUFF((SELECT ',' + QUOTENAME(monthyear)
FROM (SELECT DISTINCT (LEFT(DATENAME(MONTH, month_start),3)+ '-' + CONVERT(VARCHAR, DATEPART(YEAR, month_start))) AS monthyear, month_start
FROM dbo.mo_vendor_month WITH(NOLOCK)
WHERE vend_id = #arguments.prospectId#
AND month_start >= '#startDate#'
)alertsMonths
ORDER BY month_start ASC
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET #query = 'SELECT ' + #cols + '
FROM
(
SELECT total_unique_leads,(LEFT(DATENAME(MONTH, month_start),3)+ ''-'' + CONVERT(VARCHAR, DATEPART(YEAR, month_start))) AS monthyear
FROM dbo.mo_vendor_month
WHERE vend_id = #arguments.prospectId#
AND month_start >= ''#startDate#''
GROUP BY month_start, total_unique_leads
) x
pivot
(
max(total_unique_leads)
FOR monthyear IN (' + #cols + ')
) p '
EXECUTE(#query)
Just put square brackets around the field name you're constructing, like this:
"[" + (LEFT(DATENAME(month, leadtime),3) + " " + CONVERT(varchar, DATEPART(year, leadtime))) + "] as leadmonth"
I would also be ready to handle any single quotes or double quotes that might occur (by escaping them as needed when building your string). Other than that, enclosing a field name in square brackets allows you to use characters that normally would not be allowed in an identifier's name.

Update column with concatenated date (SQL Server)

I'm trying to update a column with the concatenated and converted results of two other columns in order to create a column with a date field. The SELECT statement returns the values I want to Update with, but I'm missing something (probably simple) on the update. It won't execute because
"the subquery returns more than one value".
However, I don't want to update with the same value for each row, but rather the concatenated result for each row.
What am I missing?
UPDATE myTable
SET myDate =
(
SELECT
CONVERT (Date,(CONVERT (NVarchar, CreatedYear) + '-' + CONVERT (NVarchar, CreatedMonth) + '-' + '01') ,0)
FROM myTable
)
I believe you have an extra SELECT that is not required. Please try:
UPDATE myTable
SET myDate =
CONVERT (Date,(CONVERT (NVarchar, CreatedYear) + '-' + CONVERT (NVarchar, CreatedMonth) + '-' + '01') ,0)
FROM myTable
This is a bit more readable in my opinion:
UPDATE dbo.tblControlMaster SET AuditAddDate = CAST(CreatedYear AS NVARCHAR(4)) + '-' + CAST(CreatedMonth AS NVARCHAR(2)) + '-' + '01'

how to parse for more than 4 positions

I have a funny case where a piece of data needed, is actually embedded in a column of data looking something like this:
note that is a shop with strong legacy mess still in place.
adlu201008270919_3.zip the date is what i need and is embedded.
I have code to do this here:
AND CAST(SUBSTRING(M.MDS_FILE,5,4) + '-' + SUBSTRING(M.MDS_FILE,9,2) + '-' + SUBSTRING(M.MDS_FILE,11,2) as datetime)
But now I find out that where you have here 'adlu' that is 4 pos. It can be 3 or 2 or 1.
So I have to code for that I have come up with this: but it's not compiling:
AND CASE WHEN WHEN CAST(SUBSTRING(M.MDS_FILE,5,4) + '-' + SUBSTRING(M.MDS_FILE,9,2) + '-' + SUBSTRING(M.MDS_FILE,11,2) as datetime)
ELSE WHEN OEN.LENGTH(S.FACILITY_KEY) = 3 THEN CAST(SUBSTRING(M.MDS_FILE,4,4) + '-' + SUBSTRING(M.MDS_FILE,8,2) + '-' + SUBSTRING(M.MDS_FILE,10,2) as datetime)
ELSE WHEN OEN.LENGTH(S.FACILITY_KEY) = 2 THEN CAST(SUBSTRING(M.MDS_FILE,3,4) + '-' + SUBSTRING(M.MDS_FILE,7,2) + '-' + SUBSTRING(M.MDS_FILE,9,2) as datetime)
ELSE CAST(SUBSTRING(M.MDS_FILE,2,4) + '-' + SUBSTRING(M.MDS_FILE,6,2) + '-' + SUBSTRING(M.MDS_FILE,8,2) as datetime) END
CASE requires an evaluation. Your first statement just says WHEN(a bunch of conversions) but there's never an evaluation (=, <, > etc).
I'm assuming you want that to be AND CASE WHEN OEN.LENGTH(s.FACILITY_KEY) = 4 THEN ...
Instead of a CASE statement based of S.FACILITY_KEY, I would use PATINDEX to dynamically find the start position of the date string that you're looking for:
DECLARE
#TestValue1 VARCHAR(50),
#TestValue2 VARCHAR(50),
#TestValue3 VARCHAR(50),
#TestValue4 VARCHAR(50)
SET #TestValue1 = 'adlu201008270919_3.zip'
SET #TestValue2 = 'adl201008270919_3.zip'
SET #TestValue3 = 'ad201008270919_3.zip'
SET #TestValue4 = 'a201008270919_3.zip'
SELECT CAST(SUBSTRING(#TestValue1, PATINDEX('%[1-2][0-9][0-9][0-9][0-9][0-9][0-9][0-9]%', #TestValue1), 8) AS DATETIME)
SELECT CAST(SUBSTRING(#TestValue2, PATINDEX('%[1-2][0-9][0-9][0-9][0-9][0-9][0-9][0-9]%', #TestValue2), 8) AS DATETIME)
SELECT CAST(SUBSTRING(#TestValue3, PATINDEX('%[1-2][0-9][0-9][0-9][0-9][0-9][0-9][0-9]%', #TestValue3), 8) AS DATETIME)
SELECT CAST(SUBSTRING(#TestValue4, PATINDEX('%[1-2][0-9][0-9][0-9][0-9][0-9][0-9][0-9]%', #TestValue4), 8) AS DATETIME)

transform sql query to oracle

i have to transform some query i´m using in SQL to Oracle code. I´m having a lot of trouble with tis. Does anyone know any Query transformer o something like that?. Can someone translate some part of this code for me?.
This is the code:
SELECT PRUEBA = CASE (SELECT TIMEATT FROM READER WHERE PANELID = DEVID AND READERID =
MACHINE) WHEN '1' THEN 'P10' ELSE 'P20' END
+ '0001'
+ CAST(YEAR(EVENT_TIME_UTC)AS VARCHAR)
+ Right('0' + Convert(VarChar(2), Month(EVENT_TIME_UTC)), 2)
+ Right('0' + Convert(VarChar(2), DAY(EVENT_TIME_UTC)), 2)
+ Right('0' + Convert(VarChar(2), DATEPART(HOUR,EVENT_TIME_UTC)), 2)
+ Right('0' + Convert(VarChar(2), DATEPART(MINUTE,EVENT_TIME_UTC)), 2)
+ Right('0' + Convert(VarChar(2), DATEPART(SECOND,EVENT_TIME_UTC)), 2)
+ CAST(YEAR(EVENT_TIME_UTC)AS VARCHAR)
+ Right('0' + Convert(VarChar(2), Month(EVENT_TIME_UTC)), 2)
+ Right('0' + Convert(VarChar(2), DAY(EVENT_TIME_UTC)), 2)
+ Right('0' + Convert(VarChar(2), DATEPART(HOUR,EVENT_TIME_UTC)), 2)
+ Right('0' + Convert(VarChar(2), DATEPART(MINUTE,EVENT_TIME_UTC)), 2)
+ Right('0' + Convert(VarChar(2), DATEPART(SECOND,EVENT_TIME_UTC)), 2)
+ Right('00000000' + Convert(VarChar(8), CARDNUM), 8)
+ Right('00000000' + Convert(VarChar(8), (SELECT SSNO FROM EMP WHERE ID = EMPID)), 8),
FROM events
WHERE eventid = 0 AND eventid = 0
and machine in (11) AND DEVID IN (1,2)
and CARDNUM <> 0 AND EMPID <> 0
and EVENT_TIME_UTC between '2006-02-16' AND '2007-02-09'
Many thanks for your help, i´ll keep looking.
Try this:
SELECT CASE (SELECT timeatt FROM reader WHERE panelid = devid AND readerid =
machine)
WHEN '1' THEN 'P10'
ELSE 'P20'
END
|| '0001'
|| To_char(event_time_utc, 'RRRRMMDDHH24MISS')
|| To_char(event_time_utc, 'RRRRMMDDHH24MISS')
|| Lpad(cardnum, 8, '0')
|| Lpad((SELECT ssno
FROM emp
WHERE id = empid), 8, '0') AS prueba
FROM events
WHERE eventid = 0
AND eventid = 0
AND machine IN ( 11 )
AND devid IN ( 1, 2 )
AND cardnum <> 0
AND empid <> 0
AND event_time_utc BETWEEN TO_DATE('2006-02-16', 'RRRR-MM-DD') AND TO_DATE('2007-02-09', 'RRRR-MM-DD')
I have recently had to make the same conversion from a life in tSQL to plSQL (oracle). A couple of "gotcha's" in the code you posted:
1) In tSQL the plus sign (for concatenation)+ is replaced in plSQL with double pipe ||
2) Most of the time you need a "Reference Cursor" (REF CURSOR) declared to put your results into like
PROCEDURE DEMO_SELECT_4_SO(
//other parameters followed by//
P_RESULT OUT REF CURSOR)
IS
BEGIN
OPEN P_RESULT FOR
SELECT
//fields///
FROM
a_table
WHERE
//you want..//
OR (as with a scalar result like your query) a single parameter of the correct type, like:
PROCEDURE DEMO_SELECT_4_SO(
//other parameters followed by//
P_RESULT OUT varchar2(60))
IS
BEGIN
SELECT
//concatenated fields///
INTO
P_RESULT
FROM
a_table
WHERE
//you want..//
NOTICE That select into in plSQL assigns the selected value to the target parameter and does not create a table as it would in tSQL
3) RIGHT (or LEFT) are SUBSTR functions in plSQL
I have found a lot of utility out of this link http://www.techonthenet.com/oracle/index.php for clear explanations of plSQL.