How to compare 2 NVARCHAR(MAX) columns in same table ?
I have 2 strings i am trying to compare them ,If user changes some data then insert should happen to change log table .
here is the condition i am using it
If dbo.RemoveMultipleSpacesItr(@ProgBusSolPrev) <> dbo.RemoveMultipleSpacesItr(@ProgBusSol)
begin
Insert into ptt_pmt_import_ch(ProgramID,ColumnName,Prev_Value,New_Value,UpdatedBy) values(@Programid,'Solution to Problem',@ProgBusSolPrev,@ProgBusSol,@UpdatedBy)
end
My Scalar Function to compare 2 strings and replace spaces in strings.
CREATE FUNCTION dbo.RemoveMultipleSpacesItr(@str NVARCHAR(MAX))
RETURNS NVARCHAR(MAX)
AS
BEGIN
WHILE CHARINDEX(' ', @str) > 0
SET @str = REPLACE(@str, ' ', '');
RETURN @str;
END
If my Input values for
@ProgDescriptionPrev='These issues are creating missed appointments and unnecessary scheduling techs on appt that are not needed. This impacts areas that are in an overbooking situation. Potentially overbooks appts during specific time of day, and increases Appt misses. Potentially decreasing Appts met by .3%, which has potential customer services impacts of 10K per year. This impacts Load Supervisors as they have to manually calculate worksteam percentage allocations. Estimating 20 users a day * 30mins= 50hrs week =1.1 Supervisor HC= 90K year. IT HelpDesk Tickets (sometimes duplicate) are also opened by front-line agents and are unable to be resolved. So this is a total of about 100k+ a year in cost savings/avoidance.'
@ProgDescription='These issues are creating missed appointments and unnecessary scheduling techs on appt that are not needed. This impacts areas that are in an overbooking situation. Potentially overbooks appts during specific time of day, and increases Appt misses. Potentially decreasing Appts met by .3%, which has potential customer services impacts of 10K per year. This impacts Load Supervisors as they have to manually calculate worksteam percentage allocations. Estimating 20 users a day * 30mins= 50hrs week =1.1 Supervisor HC= 90K year. IT HelpDesk Tickets (sometimes duplicate) are also opened by front-line agents and are unable to be resolved. So this is a total of about 100k+ a year in cost savings/avoidance.'
Only difference in strings is space(' ')
if there is no difference in strings avoiding spaces in strings, i need to insert into change log. But using above query even there is no change in string values it inserts in to change log table.Please help on this,i need solution for this
sonali malla
Hi,,,
Are you lecturing my dynamic script? Thither is a solution for this problem - we can convert all column values to nvarchar(max) first - most common types can be converted to nvarchar(max) and only some exotic types cannot be converted.
Here is the script using nvarchar(max):
CREATE TABLE Test1(id INT,col2 INT,col3 INT, col4 int, col5 varchar(10), col6 date)
CREATE TABLE Test2(id INT,col2 INT,col3 INT, col4 int, col5 varchar(10), col6 date)
INSERT INTO Test1 VALUES (1,2,3,9,'q', '20120101'),(4,5,6,10,'z','20120404')
INSERT INTO Test2 VALUES (1,2,7,8, 'm','19990101'),(4,8,6,12, 'dd','20110505')
declare @sql nvarchar(max), @Cols nvarchar(max)
select @Cols = stuff((select ',(cast(' + QUOTENAME(column_name) + ' as nvarchar(max)),' +
QUOTENAME(column_name,'''') + ')' from Information_schema.columns C
where C.TABLE_SCHEMA = 'dbo' and c.TABLE_NAME = 'Test1' and c.COLUMN_NAME <> 'id'
order by c.COLUMN_NAME for XML path('')),1,1,'')
set @sql = 'SELECT t1.c as [Column Name] , t1.col as [Expected Value], t2.col as [Actual Value]
FROM (select id, c, col from Test1 cross apply (values' + @Cols + ' ) d(col, c) ) t1
INNER JOIN
(select id, c, col from Test2 cross apply (values' + @Cols+ ' ) d(col, c) ) t2
ON t1.id=t2.id AND t1.c=t2.c
WHERE t1.col<>t2.col
Order by t1.c'
print @sql
execute (@sql)
If Any other Concern, let me know.
Thanks :-)
Similar Messages
-
How to compare SSIS Variable and Column In the table!!.
Hi Folks,
My Requirement IS :
1<sup>st</sup>run: if the record does not exist
in the table insert the record (file_name, last_modified_file_date) and create a copy in the archive folder with file_name_currentdate.csv
Daily run:
retrieve the last_modified_file_date from the input file and check if the retrieved date is greater than the last_modified_file_date in the table:
If true:
create a copy of the input file in the archive folder and update the last_modified_file_date in the table with the retrieved date
If false don’t do nothing because the file has been archived in one of the previous runs.
I have already retrieving the modified date and File Nae iserting into Filename Table: (That table has 2 columns which are FileName and FileDate) so In script task everytime the variable getting Modified date(retrieve the last_modified_file_date
from the input file) could yu please give me idea after that how I can Compre the existing table record and variable. I have already
imported the all Filenames and Modified into table like below.
Could you please give your ideas friends.Try this:
1) Execute SQL Task (In the Parameter mapping, pass filename and fileLastModified date retrieved from the file - your SSIS Variable)
2) In the ‘SQL statement’, Write a TSQL like this:
--declare these variables before the use
SET @filename=?
SET @fileLastModifieddate=?
--declare @MaxLastTblDate and @flag=0
select @MaxLastTblDate = Max(last_modified_file_date) from Table T1
If (@fileLastModifieddate>@MaxLastTblDate)
--Do your insert here
--Update the variable with @flag (say 1)
3) Set the value of @flag in the Result set of Execute SQL (another SSIS variable)
4) In the next control flow component, do the file archiving.
5) Between these two components, check the value of the @flag variable in the precedence constraints (whether to copy the file for archiving or not)
Hope this helps. -
Need to compare values in two columns of one table against values in two columns in another table
Hi, as the title reads, I'm looking for an approach that will allow me to compare values in two columns of one table against values in two columns in another table.
Say, for instance, here are my tables:
Table1:
Server,Login
ABCDEF,JOHN
ABCDEF,JANE
FEDCBA,SEAN
FEDCBA,SHAWN
Table2:
Server,Login
ABCDEF,JOHN
ABCDEF,JANE
FEDCBA,SHAWN
In comparing the two tables, I'd like my query to report the rows in table1 NOT found in table2. In this case, it'll be the 3rd row of table one:
Server,Login
FEDCBA,SEAN
Thanks.create table Table1([Server] varchar(50), Login varchar(50))
Insert into Table1 values ('ABCDEF','JOHN'),('ABCDEF','JANE'),('FEDCBA','SEAN'),('FEDCBA','SHAWN')
create table Table2([Server] varchar(50), Login varchar(50))
Insert into Table2 values ('ABCDEF','JOHN'),('ABCDEF','JANE'), ('FEDCBA','SHAWN')
select [Server] ,Login from Table1
Except
select [Server] ,Login from Table2
select [Server] ,Login from Table1 t1
where not exists(Select 1 from Table2 where t1.[Server] = t1.[Server] AND Login=t1.Login)
drop table Table1,Table2 -
How to compare index names and columns from different user?
I am using below query to compare two indexes from 2 different users but even though index name and columns are same... result shows me they are different.. what I am doing wrong? Thanks
WITH t AS
(SELECT COUNT (DISTINCT index_owner || index_name || indexed_cols)
cnt
FROM ( SELECT index_owner,
index_name,
listagg (column_name, ',')
WITHIN GROUP (ORDER BY column_position)
indexed_cols
FROM dba_ind_columns
WHERE index_name='XPKTBL_A'
GROUP BY index_owner, index_name))
SELECT CASE
WHEN cnt > 1 THEN 'Indexes are different'
WHEN cnt = 0 THEN 'Indexes dont exist'
WHEN cnt > 1 THEN 'Indexes are identical'
END
commnt
FROM t
Result:
Indexes are different
but Actually if you check below they are same After when I run this query:
SELECT index_owner,
index_name,
listagg (column_name, ',') WITHIN GROUP (ORDER BY column_position)
indexed_cols
FROM dba_ind_columns
WHERE index_name='XPKTBL_A'
GROUP BY index_owner, index_name;
Result:
Index_owner
Index_name
Index_cols
USER1
XPKTBL_A
FIELD_A1
USER2
XPKTBL_A
FIELD_A1Hi,
Erhan_toronto wrote:
I am using below query to compare two indexes from 2 different users but even though index name and columns are same... result shows me they are different.. what I am doing wrong? Thanks
WITH t AS
(SELECT COUNT (DISTINCT index_owner || index_name || indexed_cols)
So index_owner is 'USER1' in one case, and 'USER2' in the other; right?
A string that starts with 'USER1' will be distinct from a string that starts with 'USER2', no matter what the rest of the string contains. Maybe you don't want to compare the owners, or maybe you meant to use some other column (such as table_name) instead of index_owner).
I hope this answers your question.
If not, post a little sample data (CREATE TABLE, CREATE INDEX and CONNECT statements), and also post the results you want from that data.
Explain, using specific examples, how you get those results from that data.
Always say which version of Oracle you're using (e.g., 11.2.0.2.0).
See the forum FAQ: https://forums.oracle.com/message/9362002 -
Compare two records column by column in same table
Hi All,
I have an address table with ID as the PK but there can be more than one ID. I need to take the latest address record and first see if that same ID has a previous address record and if so, compare each column to see if the data has changed. I only need to compare the latest record with the next latest record.
I cannot figure this out at all. I can of course use the MAX function to get the latest address records but do not know how I can pull the next latest address record that matches the ID and compare each column.
Sample table:
ID street city state zip effective_date
1 123 main chicago IL 60111 3-7-2012
2 34 N 13th new york NY 18374 3-7-2012
3 15 N main Dallas TX 47389 3-7-2012
1 89 N main chicago IL 60111 1-5-2012
1 16 East St columbus OH 47382 12-10-2011
2 34 N 13th new york NY 18374 10-7-2011
2 15 S Elm new york NY 18374 09-1-2011
3 15 N main Dallas TX 47389 10-4-2011
SO...in the table above using today as the latest record date, based of my criteria I would only want to pull record ID 1 and 2 since the next most recent record for those IDs have had at least one of their address data change. ID 3 has exactly the same address data so I would not consider that in my criteria.
Can i do this with SQL only or will i need to create a procedure or function?
Any help is appreciated
BenBen C wrote:
Hi All,
I have an address table with ID as the PK but there can be more than one ID. You mean there can be more than one row with tha same ID, right? (There can be more than one ID, also.)
I need to take the latest address record and first see if that same ID has a previous address record and if so, compare each column to see if the data has changed. I only need to compare the latest record with the next latest record.
... Sample table:Whenever you have a problem, please post CREATE TABLE and INSERT statements for the sample data, and the exact results you want from that data.
Explain, using specific examples, how you get those results from that data.
Always say which version of Oracle you're using.
Can i do this with SQL only or will i need to create a procedure or function?You don't need PL/SQL, if I understand your requirements. You can do something like this:
WITH got_analytics AS
SELECT id, street, city, state, zip, effective_date
, COUNT (*) OVER ( PARTITION BY id ) AS cnt
, ROW_NUMBER () OVER ( PARTITION BY id
ORDER BY effective_date DESC
) AS r_num
FROM table_x
-- WHERE ... -- If you need any filtering, put it here
SELECT id, street, city, state, zip, effective_date
FROM got_analytics
WHERE cnt > 1
AND r_num <= 2
ORDER BY id
, effective_date
;This will show the most recent 2 rows for each id that has 2 (or more) rows.
You can modify it to only include ids where there was some change in street, city, state or zip between those 2 rows.
WITH got_analytics AS
SELECT id, street, city, state, zip, effective_date
, COUNT (*) OVER ( PARTITION BY id ) AS cnt
, ROW_NUMBER () OVER ( PARTITION BY id
ORDER BY effective_date DESC
) AS r_num
FROM table_x
-- WHERE ... -- If you need any filtering, put it here
, got_unique_cnts AS
SELECT id, street, city, state, zip, effective_date
, COUNT (DISTINCT '~' || street) OVER (PARTITION BY id) AS street_cnt
, COUNT (DISTINCT '~' || city) OVER (PARTITION BY id) AS city_cnt
, COUNT (DISTINCT '~' || state) OVER (PARTITION BY id) AS state_cnt
, COUNT (DISTINCT '~' || zip) OVER (PARTITION BY id) AS zip_cnt
FROM got_analytics
WHERE cnt > 1
AND r_num <= 2
SELECT id, street, city, state, zip, effective_date
FROM got_unique_cnts
WHERE street_cnt > 1
OR city_cnt > 1
OR state_cnt > 1
OR zip_cnt > 1
ORDER BY id
, effective_date
;This assumes that street, city, state and zip are all VARCHAR2s. If any of those columns is NULL on one row, and not NULL on the other row for that ID, that counts as a difference.
Edited by: Frank Kulash on Mar 7, 2012 3:37 PM
Edited by: Frank Kulash on Mar 7, 2012 3:41 PM -
Create ViewCriteria comparing two columns from same table
Does anyone know how I can create a ViewCriteria where clause that compares two columns from the same table?
For example if I had two integer columns (MINSAL and MAXSAL) and wanted to see if they are equal. I would normally do the following SQL below.
SELECT * FROM EMPL
WHERE MINSAL = MAXSALIt works, but it is not ideal.
Setup a Transient column that performs a groovy evaluation of MINSAL=MAXSAL and then my ViewCriteria evaluates the column to true and I set Query Execution Mode to Both. -
Compare combintaion of two columns in two tables for duplicates
Compare company+model combination in dbo.cars table with company+Model combination in dbo.details and update the Duplicate column in dbo.cars with ‘Y’ if the combination is already there in dbo.details table
dbo.cars
dbo.details
Company
Model
Released
Duplicate
Company
Model
Year
Price
Nissan
N2011
2011
Nissan
N2011
2011
30000
Honda
H2013
2013
Honda
H2012
2013
31000
Toyota
T2009
2009
Toyota
T2010
2009
32000
For Example: In the above table only Nissan column should have ‘Y’ bcoz Nissan+N2011 exists in both table.
dbo.cars
dbo.details
Company
Model
Released
Duplicate
Company
Model
Year
Price
Nissan
N2011
2011
Y
Nissan
N2011
2011
30000
Honda
H2013
2013
Honda
H2012
2013
31000
Toyota
T2009
2009
Toyota
T2010
2009
32000
How to achieve this
Thanks in advanceTry the below:
SElect A.*,Case when B.Model is not null then 'Y' else '' end as duplicate From dbo.Cars A
Left Join dbo.details B on A.company= B.Company and A.Model = B.Model
To Update the values:
create table Cars (company varchar(100),model varchar(100),Duplicate char(1))
Insert into Cars(Company,model) Select 'Nissan','2011'
Insert into Cars(Company,model) Select 'Toyota','2011'
create table details (company varchar(100),model varchar(100))
Insert into details(Company,model) Select 'Nissan','2011'
Insert into details(Company,model) Select 'Toyota','2012'
update A Set Duplicate = Case when B.Model is not null then 'Y' else '' end
From dbo.Cars A
Left Join dbo.details B on A.company= B.Company and A.Model = B.Model
Select* From Cars
Drop table Cars,details -
How to Insert Image in a Column of a table
Hi
I have read several documentations but still could not find any relevant one that can help me in inserting a image in a BLOB column of a table.I have read about DBMS_LOB but still not clear how to insert an image in the table.
I followed following steps :
create table Emp_Identity(Id Number,Photo BLOB);
Insert Into Emp_Identity(1,'d:\vishal.bmp');
Please tell me steps to be followed.
Regards
Vishal Chaudhry
nullI am using Developer 2000 Forms 6i as Front End (Oracle 8.1.6)
My table structure is:
SQL> desc test_lob
Name Data Type
ID NUMBER
NAME VARCHAR2(100)
PHOTO BLOB
SOUND BINARY FILE LOB
IS there any way to display the BFILE contents on the frontend.....?
<BLOCKQUOTE><font size="1" face="Verdana, Arial, Helvetica">quote:</font><HR>Originally posted by vishal chaudhry ([email protected]):
Hi,
I could actually insert an image in a BLOB type column from the backend(Sql plus) not directly but by using BFILE and see that image on the frontend (Forms 6i Developer 2000,Item type is Image as there is nothing like BLOB/BFILE in front end) using the following procedure :
IS there any way I can insert an image directly in a BLOB column from the backend rather than using BFILE?
CREATE OR REPLACE PROCEDURE loadLOBFromBFILE_proc IS
Dest_loc BLOB;
Src_loc BFILE := BFILENAME('SOUND_DIR', '123w.bmp');
** SOUND_DIR is a logical directory created by giving path of the server
** Create Directory SOUND_DIR as 'd:\u020\o816\ctx\test'
** d:\u020\o816\ctx is the physical path of the server \\pslndb\ctx$
** test is the dummy testing directory created on the server
** 123w.bmp is lying in the test directory
Amount INTEGER ;
BEGIN
Amount := DBMS_LOB.GETLENGTH(Src_loc);
SELECT photo INTO Dest_loc FROM test_lob
WHERE ID = 1
FOR UPDATE;
/* Opening the source BFILE is mandatory: */
DBMS_LOB.OPEN(Src_loc, DBMS_LOB.LOB_READONLY);
/* Opening the LOB is optional: */
DBMS_LOB.OPEN(Dest_loc, DBMS_LOB.LOB_READWRITE);
DBMS_LOB.LOADFROMFILE(Dest_loc, Src_loc, Amount);
/* Closing the LOB is mandatory if you have opened it: */
DBMS_LOB.CLOSE(Dest_loc);
DBMS_LOB.CLOSE(Src_loc);
COMMIT;
END;
<HR></BLOCKQUOTE>
null -
How to show icon in a column of a table?
How to display an icon in a column of a table UI element and this icon is to be displayed based on values in the table row?
I normally use a calculated attribute inside the table's data source node for this.
Add an attribute "Icon", type=string, calculated=true, read-only=true, under the data source node.
(If the data source node uses structure binding and does not allow to add an attribute, add a helper value node instead, cardinality=1:1, selection=1:1, and add the attribute to this node.)
In the get-method for the calculated attribute, you get the node element corresponding to the table row as parameter. Depending on other attributes in this node element, select an icon URL and return it.
If you put your icons inside the src/mimes/<component> folder, you can simply return the file name of the icon.
Don't use a Button as table cell editor but rather an Image or LinkToAction.
Armin -
How to add description of a column of a table in SQL Azure
Hi
I have some tables in my application database where there are descriptions added against certain columns. Needless to say they were done by using sp_addextendedproperty.
Now I am trying to migrate the Database to SQL Azure. SQL Azure does not support sp_addextendedproperty.
Hence I am not able to figure out how to add descriptions to those columns.
Any help would be much appreciated.
Thanks
SoumyadebHello,
Just as Latheesh post above, Windows Azure SQL database are not support extended stored procedures. That’s one of the limitations on SQL database, and I don’t know there is another way to achieve the same on Azure.
Regards,
Fanny Liu
Fanny Liu
TechNet Community Support -
How to get the selected rows & columns in the table?
hi everybody,
In my application the table is kept inside the event structure.I select the cells in the table (using mouse) on running time.How to get the selected number of rows & columns in that table?Hello,
You can fill selected values of the table by writing to it or the corresponding property using a property node - the table is just a 2D array of strings. I think for your "disable" question you are referring to the shortcut menu (when you right click). If you are using LabVIEW 8.x, you can edit or disable that shortcut menu - just right click on your table at edit time and choose Advanced >> Run-Time Shortcut Menu.
Best Regards,
JLS
Best,
JLS
Sixclear -
How to grey out one single column in a table control of TPMOE
Hi Experts,
Any body please tell me how to greyout a single column in a table control of TPMOE.
Help needed ASAP.
Thanks,
sreenivas.lr_result TYPE REF TO if_bol_bo_property_access
lr_iterator TYPE REF TO if_bol_bo_col_iterator
CALL METHOD lr_iterator->get_by_index
EXPORTING
iv_index = index
RECEIVING
rv_result = lr_result.
CALL METHOD lr_result->get_property_as_value
EXPORTING
iv_attr_name = 'TRANSFER_STATUS'
IMPORTING
ev_result = lv_status.
if lv_status = x and component = cost_category.
rv_disabled = true.
else.
call super.
endif.
INDEX will have the row number.
Frame ur logic based on this. -
How to find the frequently updated columns in a table
Hi ,
I need to find out all the columns of a tables which are frequently getting updated.
is there any way that I can achieve this ? I am not sure if any meta data information for DML operations exist in Oracle 9 i. Any input is welcome.
Thanks in Advance !!Thank u , i am thinking the same, Thanks for the suggestion.
any other idea.... like is there any system table which we can query to get details about these dml operations on a table ?are there any kind of system audit tables in oracle where these get recorded ? -
How to find out the NULL columns in the table?
Hi,
Please provide the query to find the null columns in the table. Here, all rows in the table have same column as null. It won't change.
Table
c1 c2 c3 c4
X C 10
T D 20
I wanna find out as C2 is the nullable column.
Thanks in advance !!
Regards,
Vissu....Below code might be solution for finding NULL valued in columns in a table and if it is solution .kindly give me points for the same.
declare
cursor col_cur is
select column_name
from user_tab_cols -- all_tables can also be used in case the table is present in own schema
where table_name = 'TABLE_NAME'; --provide the TABLE_NAME
stmt varchar2(1000):= '';
v_count number;
count_null number;
begin
execute immediate 'select count(*) from TABLE_NAME' into v_count; --provide the TABLE_NAME
for rec in col_cur loop
execute immediate 'select count(*) from TABLE_NAME' where --provide the TABLE_NAME
'||rec.column_name||' IS NULL' into count_null;
if count_null = v_count then
stmt :=stmt|| rec.column_name ||chr(13);
end if;
end loop;
dbms_output.put_line(stmt);
end ; -
How can I find number of columns in a table using a query
Hi
I want to find the number of columns in a table using a query.
Any help in this regard is much appreciated.
CheersHi,
This is the output i get when i executed ur query
OWNER OBJECT_NAME OBJECT_TYPE
SMLDBO T2311_SURVEY_QUESTIONS TABLE
select OWNER,OBJECT_NAME,OBJECT_TYPE
from all_objects
where OBJECT_NAME = 'T2311_SURVEY_QUESTIONS';
works Fine.
But if i use the below query it returns : 0
SELECT count(*) FROM user_tab_columns
WHERE table_name =upper( 'T2311_SURVEY_QUESTIONS');
What could be problem.
The table exists + name of the table is correct + it resides in my schema itself.
Any guess !!!
Maybe you are looking for
-
Web Dynpro SRM 7.0 - Access Shopping Cart One Screen User Default Settings
Hi all, In my current project I have a requirement which includes to validate the user default values on shop on one screen functionality, my question is, how can I access to this information? In web dynpro there's no reference to this information an
-
How to share folder with only one person one same Mac
Could someone please remind me how I share a folder with one person I share my Mac with but not the others (we all have different profiles on the same machine...) Thanks, Michael
-
Contacts and Calendar Server, Pointless?
Hello! MLS N00B here, not really much experience with ML Server. Only had it a few weeks, and the new Profile Managaer instead of WGM thing really messed me around, seems unstable and a little too new. Anyway. Todays discussion comes in the shape of
-
Just got a new hard drive that I wasn't anticipating and yep, I lost a lot of stuff. Trying like a maniac to get back what I had, including programs. My MacBook Pro is mid 2009 (or Sept. 2009) and it has Mavericks on the new HD. My old one (Leopard o
-
Java.lang.stackoverflow error
Hi All, I am getting the following error Exception in thread "main" java.lang.StackOverflowError at java.util.ArrayList.<init>(Unknown Source) at com.migration.wcm.vigneete.InitializeCls.<init>(InitializeCls.java:12) at com.migration.w