Saturday, 10 March 2018
To know Compatibility Level of DB in SQL
SELECT compatibility_level
FROM sys.databases WHERE name = 'srs1';
ALTER DATABASE srs1
SET COMPATIBILITY_LEVEL = 100
FROM sys.databases WHERE name = 'srs1';
ALTER DATABASE srs1
SET COMPATIBILITY_LEVEL = 100
Interview Questions faced in 2018 on MS.NET
SQL Server:
1. How will you get same result as Union All of table(tblA and tblB) with out using Union All?
2. Differents between Temp Table and Table Variable?
3.What is Unique key?
4.What is Primary key?
5.Differents between Function and SP?
6.Differents between Group by, Partition and Rank in SQL?
7.How to update two different table's column at same time using same query?
8.How to update one table's column as bit, update 0 to 1, 1 to 0 at same time?
Eg.
column1
0 to 1
1 to 0
Capgemini
9.What is Index?
10.How many types of Indexes?What are they?
11.How many Cluster Index will you able create in one table?
12.How many Non Cluster Index will you able create in one table?
http://sql-plsql.blogspot.in/2013/08/multiple-choice-questions-sql-indexes.html
13.Differents between Function and SP?
14.How to handle Exception in SQL?
15.What is Transaction in SQL?
Example:
16.Write a query to get Max Salary of employee in SQL Server?
Answer:
select * from(
select row_number() over (order by salary) as sal_level,Salary from #tempEmp) A
where A.sal_level=10
17.How to Execute Function to see the result in SQL?
Answer:
declare @aaa varchar(50)
select @aaa= dbo.Func_1(904977, '2018-02-25 00:00:00.000')
select @aaa
Go
select dbo.Func_1(904977, '2018-02-25 00:00:00.000')
OOPs :
1.What is Polymerphism?
2.Differents between Overloading and Overriding?
3.What is Static class?
4.What is Constructor?
5.Is it possible to use Static with Sealed Class?
6.What is Copy Constructor?
7.Differents between ref and out parameter?
8.How Destructor internally used?
Capgemini
9.What is Abstract in c#?
10.What is Polymerphism?
C#:
1.What is Anonymous function?
2.what is 'using' and where do you used it in c#?
3.What is IList and List in c#?
4.What is IEnumerable in c#?
5.What is IQuerable in c#?
6.What is LINQ in c#?
7.What is Collection in c#?
8.What is Generic in c#?
HCL
9.Example of Multiple Inheritance in c#?
Dell
10.Why String and string?
11.You have two .cs file, (A.cs and B.cs file), so how will you get classes of A.cs in to B.cs?
JQuery:
1.Differents between DataType and ContentType?
HCL
2.You have 5 hyper link and 5 Paragraph, Onclick particular hyperlink only show related Paragraph others should hide?
Dell
3.Differents between JS and JQuery?
JavaScript:
Dell
1.Differents between JS and JQuery?
2.Write a query to check palindrome in JS?
3.What is the Pageload function in JS?
//JS
<script type="text/javascript">
function SomeFunction() {
/* do stuff on page load */
}
window.onload = SomeFunction;
</script>
// jQuery
<script type="text/javascript">
SomeFunction();
</script>
$(document).ready( function () {
SomeFunction();
});
CSS:
Capgemini
1.What is Z-Index?
2.What is 'absolute'?
Hint: In Position we use absolute.
-2
-1
Z-Index:0(default)
1
2
Logical:
HCL
1.Write a logic to check Palindrome?
2.Write a logic to Reverse string with out using Array and any Built in function?
3.* Pattern?
Karvy:
1.How do you know that Class/Method is belongs to particular Interface?
Eg:
Interface A
{
int Add(int A,int B)
}
Interface B
{
int Add(int A,int B)
}
Class A:Interface A,Interface B
{
Here how do you know below class is belongs to Interface A or Interface B?
public int Add(int A,int B)
{
return A+B;
}
}
2. Can you able to create instance of Interface?
3.What are the J Query properties, and how to disable textbox?
4.Serialization and De-serialization in c#?
5.How to send data from Controller to Controller in MVC?
Savvy It Solution:
1. Syntax of Session?
2. Differences between Abstract and Interface, when to use Abstract and Interface?
3. How to send data from View to Controller and vice versa?
4. How to send data from Controller to Controller and vice versa?
5. Sql: Write a query to get Super Manager of an Employee?
Eg: Emp table
EmpId EName MgrId
100 Subs 400
400 Naresh 300
300 Venkat 200
200 Pani 100
100 Kumar Null
So here Mgr of ' Employee Subs' is Naresh, and Super Mgr is 'Employee Venkat'.
Ans:
Select A1.* from #tblTemp A1 --3rd Inner Join(To get third super MgrId of Emp)
inner join
(Select E1.* from #tblTemp E1 --2nd Inner Join(To get second super MgrId of Emp)
inner join
(Select Emp1.Ename,Emp1.MgrId --1st Self Join(To get first MgrId of Emp)
from #tblTemp Emp1,#tblTemp Emp2
where Emp1.EId=Emp2.MgrId
and Emp1.EId=100) E2 on E2.MgrId=E1.EId) A2 on A2.MgrId=A1.Eid
1. How will you get same result as Union All of table(tblA and tblB) with out using Union All?
2. Differents between Temp Table and Table Variable?
3.What is Unique key?
4.What is Primary key?
5.Differents between Function and SP?
6.Differents between Group by, Partition and Rank in SQL?
7.How to update two different table's column at same time using same query?
8.How to update one table's column as bit, update 0 to 1, 1 to 0 at same time?
Eg.
column1
0 to 1
1 to 0
Capgemini
9.What is Index?
10.How many types of Indexes?What are they?
11.How many Cluster Index will you able create in one table?
12.How many Non Cluster Index will you able create in one table?
http://sql-plsql.blogspot.in/2013/08/multiple-choice-questions-sql-indexes.html
13.Differents between Function and SP?
14.How to handle Exception in SQL?
15.What is Transaction in SQL?
Example:
CREATE PROCEDURE UpdateSales
@SalesPersonID INT,
@SalesAmt MONEY = 0
AS
BEGIN
BEGIN TRY
BEGIN TRANSACTION;
UPDATE LastYearSales
SET SalesLastYear = SalesLastYear + @SalesAmt
WHERE SalesPersonID = @SalesPersonID;
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
DECLARE @ErrorNumber INT = ERROR_NUMBER();
DECLARE @ErrorLine INT = ERROR_LINE();
DECLARE @ErrorMessage NVARCHAR(4000) = ERROR_MESSAGE();
DECLARE @ErrorSeverity INT = ERROR_SEVERITY();
DECLARE @ErrorState INT = ERROR_STATE();
PRINT 'Actual error number: ' + CAST(@ErrorNumber AS VARCHAR(10));
PRINT 'Actual line number: ' + CAST(@ErrorLine AS VARCHAR(10));
RAISERROR(@ErrorMessage, @ErrorSeverity, @ErrorState);
END CATCH
END;
16.Write a query to get Max Salary of employee in SQL Server?
Answer:
select * from(
select row_number() over (order by salary) as sal_level,Salary from #tempEmp) A
where A.sal_level=10
17.How to Execute Function to see the result in SQL?
Answer:
declare @aaa varchar(50)
select @aaa= dbo.Func_1(904977, '2018-02-25 00:00:00.000')
select @aaa
Go
select dbo.Func_1(904977, '2018-02-25 00:00:00.000')
OOPs :
1.What is Polymerphism?
2.Differents between Overloading and Overriding?
3.What is Static class?
4.What is Constructor?
5.Is it possible to use Static with Sealed Class?
6.What is Copy Constructor?
7.Differents between ref and out parameter?
8.How Destructor internally used?
Capgemini
9.What is Abstract in c#?
10.What is Polymerphism?
C#:
1.What is Anonymous function?
2.what is 'using' and where do you used it in c#?
3.What is IList and List in c#?
4.What is IEnumerable in c#?
5.What is IQuerable in c#?
6.What is LINQ in c#?
7.What is Collection in c#?
8.What is Generic in c#?
HCL
9.Example of Multiple Inheritance in c#?
Dell
10.Why String and string?
11.You have two .cs file, (A.cs and B.cs file), so how will you get classes of A.cs in to B.cs?
JQuery:
1.Differents between DataType and ContentType?
HCL
2.You have 5 hyper link and 5 Paragraph, Onclick particular hyperlink only show related Paragraph others should hide?
Dell
3.Differents between JS and JQuery?
JavaScript:
Dell
1.Differents between JS and JQuery?
2.Write a query to check palindrome in JS?
3.What is the Pageload function in JS?
//JS
<script type="text/javascript">
function SomeFunction() {
/* do stuff on page load */
}
window.onload = SomeFunction;
</script>
// jQuery
<script type="text/javascript">
SomeFunction();
</script>
$(document).ready( function () {
SomeFunction();
});
CSS:
Capgemini
1.What is Z-Index?
2.What is 'absolute'?
Hint: In Position we use absolute.
-2
-1
Z-Index:0(default)
1
2
Logical:
HCL
1.Write a logic to check Palindrome?
2.Write a logic to Reverse string with out using Array and any Built in function?
3.* Pattern?
Karvy:
1.How do you know that Class/Method is belongs to particular Interface?
Eg:
Interface A
{
int Add(int A,int B)
}
Interface B
{
int Add(int A,int B)
}
Class A:Interface A,Interface B
{
Here how do you know below class is belongs to Interface A or Interface B?
public int Add(int A,int B)
{
return A+B;
}
}
2. Can you able to create instance of Interface?
3.What are the J Query properties, and how to disable textbox?
4.Serialization and De-serialization in c#?
5.How to send data from Controller to Controller in MVC?
Savvy It Solution:
1. Syntax of Session?
2. Differences between Abstract and Interface, when to use Abstract and Interface?
3. How to send data from View to Controller and vice versa?
4. How to send data from Controller to Controller and vice versa?
5. Sql: Write a query to get Super Manager of an Employee?
Eg: Emp table
EmpId EName MgrId
100 Subs 400
400 Naresh 300
300 Venkat 200
200 Pani 100
100 Kumar Null
So here Mgr of ' Employee Subs' is Naresh, and Super Mgr is 'Employee Venkat'.
Ans:
Select A1.* from #tblTemp A1 --3rd Inner Join(To get third super MgrId of Emp)
inner join
(Select E1.* from #tblTemp E1 --2nd Inner Join(To get second super MgrId of Emp)
inner join
(Select Emp1.Ename,Emp1.MgrId --1st Self Join(To get first MgrId of Emp)
from #tblTemp Emp1,#tblTemp Emp2
where Emp1.EId=Emp2.MgrId
and Emp1.EId=100) E2 on E2.MgrId=E1.EId) A2 on A2.MgrId=A1.Eid
Get 10th/nth Max salary of employee in SQL Server
Example:
create table #tempEmp(empid int identity(1,1),Salary money)
insert into #tempEmp
select 500
union
select 550
union
select 1000
union
select 1500
union
select 2000
union
select 2500
union
select 3000
union
select 3500
union
select 4000
union
select 4500
Here the Query to get 10th/nth Max salary of Employee
select * from(
select row_number() over (order by salary) as sal_level,Salary from #tempEmp) A
where A.sal_level=10
2.Second way to get the same
select max(sal) from #temp where sal in(select top 10 sal from #temp order by sal desc)
create table #tempEmp(empid int identity(1,1),Salary money)
insert into #tempEmp
select 500
union
select 550
union
select 1000
union
select 1500
union
select 2000
union
select 2500
union
select 3000
union
select 3500
union
select 4000
union
select 4500
Here the Query to get 10th/nth Max salary of Employee
select * from(
select row_number() over (order by salary) as sal_level,Salary from #tempEmp) A
where A.sal_level=10
2.Second way to get the same
select max(sal) from #temp where sal in(select top 10 sal from #temp order by sal desc)
Sunday, 25 February 2018
Example of Cursor, While Loop and Split comma all together in SQL SERVER
Declare @SBUCode2 varchar(50)
Declare @Percentage2 varchar(50)
Declare @CONTROLID2 int
Declare @countSBU int,@countPER int
Declare @SBU int,@PER numeric
Declare sBUCur cursor local scroll for Select CONTROLID,SBUCode,Percentage from #tblAcVoucherFinal where CONTROLID= @CONTROLID
open sBUCur
fetch next from sBUCur into @CONTROLID2,@SBUCode2,@Percentage2
while not @@fetch_status <> 0
Begin
--here its getting count of SBU after splitting commas
Select @countSBU= count(*) from dbo.split(@SBUCode2,',')
declare @I int=0
WHILE @I <= @countSBU-1
BEGIN
--here its getting value of SBU n Percentage as per ID from Split Function and Saving in table
Select @SBU=Value from dbo.split(@SBUCode2,',') where id=@I
Select @PER=Value from dbo.split(@Percentage2,',') where id=@I
Insert into tblAcvoucherDetails_SBU (VNo,SBUCode,Percentage,TransDate,UserID)
Values(@VNo,@SBU,@PER ,@Trans_Date,@UserID)
SET @I = @I + 1
END
fetch next from sBUCur into @CONTROLID2,@SBUCode2,@Percentage2
End
close sBUCur
deallocate sBUCur
Declare @Percentage2 varchar(50)
Declare @CONTROLID2 int
Declare @countSBU int,@countPER int
Declare @SBU int,@PER numeric
Declare sBUCur cursor local scroll for Select CONTROLID,SBUCode,Percentage from #tblAcVoucherFinal where CONTROLID= @CONTROLID
open sBUCur
fetch next from sBUCur into @CONTROLID2,@SBUCode2,@Percentage2
while not @@fetch_status <> 0
Begin
--here its getting count of SBU after splitting commas
Select @countSBU= count(*) from dbo.split(@SBUCode2,',')
declare @I int=0
WHILE @I <= @countSBU-1
BEGIN
--here its getting value of SBU n Percentage as per ID from Split Function and Saving in table
Select @SBU=Value from dbo.split(@SBUCode2,',') where id=@I
Select @PER=Value from dbo.split(@Percentage2,',') where id=@I
Insert into tblAcvoucherDetails_SBU (VNo,SBUCode,Percentage,TransDate,UserID)
Values(@VNo,@SBU,@PER ,@Trans_Date,@UserID)
SET @I = @I + 1
END
fetch next from sBUCur into @CONTROLID2,@SBUCode2,@Percentage2
End
close sBUCur
deallocate sBUCur
Execute function to see out put in Sql Server
declare @aaa varchar(50)
select @aaa= dbo.Udfgetstarttimefromorderadvancedschedule(904977, '2018-02-25 00:00:00.000')
select @aaa
select @aaa= dbo.Udfgetstarttimefromorderadvancedschedule(904977, '2018-02-25 00:00:00.000')
select @aaa
Execute SP with Out Put Parameter in Sql Server
DECLARE @return_Value int
EXEC [SP_ASSIGN_CHECK_5] 0,818645, @return_Value = @return_Value OUTPUT
SELECT @return_Value
EXEC [SP_ASSIGN_CHECK_5] 0,818645, @return_Value = @return_Value OUTPUT
SELECT @return_Value
Differents between Cast and Convert function using Sql Server
1.select distinct cast(FromDate as Varchar) FromDate from tblpolicymaster where policyno=234000211
2.select distinct Convert(Varchar,FromDate,103) FromDate from tblpolicymaster where policyno=234000211
3.using both cast & convert
select distinct cast(Convert(Varchar,FromDate,103)as varchar) FromDate from tblpolicymaster where policyno=234000211
2.select distinct Convert(Varchar,FromDate,103) FromDate from tblpolicymaster where policyno=234000211
3.using both cast & convert
select distinct cast(Convert(Varchar,FromDate,103)as varchar) FromDate from tblpolicymaster where policyno=234000211
Example of Left, Right, Charindex, Patindex using Sql Server
like left
select substring(jobdesc, 0, charindex('Teachers are not eligible for overtime because', jobdesc)) from Order_Gen where Client=48670
--1.Right
select RIGHT(CEM.ReimbHospital,CHARINDEX('-',REVERSE(CEM.ReimbHospital)) - 1) from tblClaimsEntryMaster cem WHERE cem.ClaimNo=234006607
--1.Left
select Left(CEM.ReimbHospital,CHARINDEX('-',(CEM.ReimbHospital)) - 1) from tblClaimsEntryMaster cem WHERE cem.ClaimNo=234006607
--2.Right
select right(policyname, len(policyname)-charindex('-',policyname)) from tblpolicy
select RIGHT('policy-12',9-7)
--ans->12
--2.Left
select left(policyname, charindex('-',policyname)-1 ) from tblpolicy
select LEFT('policy-12',7-1)
--ans->policy
--it returns one value
select left(ClientName,CHARINDEX(' ',ClientName)-1) from tblClientMaster where ClientNo=89 or ClientNo=71
select left('Client Name',CHARINDEX(' ','Client Name')-1)
--it returns the word frm left when see the space
select right('Client dName',CHARINDEX(' ','Client dName')-1)
--it returns the word frm right when see the space
--it returns multiple value
select left(ClientName,CHARINDEX(' ',ClientName,1)) from tblClientMaster
--it returns 1st word frm left
select right(ClientName,CHARINDEX(' ',ClientName,1)) from tblClientMaster
--it returns 1st word frm right--wrong
select CHARINDEX(' ','Client Name') --it return position of space-7
--It returns 3 letters from left and right
select left(ClientName,3) from tblClientMaster
select right(ClientName,3) from tblClientMaster
-- I need to get the last RIGHT 3 characters and I need to get whatever is to the LEFT
select right(ClientName,3),LEFT(ClientName,LEN(ClientName)-3) from tblClientMaster
-- finds the position at which the pattern ensure starts in a specific row of the Clientname column in the Document table in the AdventureWorks2012 database.
select PATINDEX('%MANSARD%',Clientname) from tblClientMaster
SELECT PATINDEX ( '%ein%', 'Das ist ein Test')
SELECT PATINDEX('%en_ure%', 'please ensure the door is locked')
select substring(jobdesc, 0, charindex('Teachers are not eligible for overtime because', jobdesc)) from Order_Gen where Client=48670
--1.Right
select RIGHT(CEM.ReimbHospital,CHARINDEX('-',REVERSE(CEM.ReimbHospital)) - 1) from tblClaimsEntryMaster cem WHERE cem.ClaimNo=234006607
--1.Left
select Left(CEM.ReimbHospital,CHARINDEX('-',(CEM.ReimbHospital)) - 1) from tblClaimsEntryMaster cem WHERE cem.ClaimNo=234006607
--2.Right
select right(policyname, len(policyname)-charindex('-',policyname)) from tblpolicy
select RIGHT('policy-12',9-7)
--ans->12
--2.Left
select left(policyname, charindex('-',policyname)-1 ) from tblpolicy
select LEFT('policy-12',7-1)
--ans->policy
--it returns one value
select left(ClientName,CHARINDEX(' ',ClientName)-1) from tblClientMaster where ClientNo=89 or ClientNo=71
select left('Client Name',CHARINDEX(' ','Client Name')-1)
--it returns the word frm left when see the space
select right('Client dName',CHARINDEX(' ','Client dName')-1)
--it returns the word frm right when see the space
--it returns multiple value
select left(ClientName,CHARINDEX(' ',ClientName,1)) from tblClientMaster
--it returns 1st word frm left
select right(ClientName,CHARINDEX(' ',ClientName,1)) from tblClientMaster
--it returns 1st word frm right--wrong
select CHARINDEX(' ','Client Name') --it return position of space-7
--It returns 3 letters from left and right
select left(ClientName,3) from tblClientMaster
select right(ClientName,3) from tblClientMaster
-- I need to get the last RIGHT 3 characters and I need to get whatever is to the LEFT
select right(ClientName,3),LEFT(ClientName,LEN(ClientName)-3) from tblClientMaster
-- finds the position at which the pattern ensure starts in a specific row of the Clientname column in the Document table in the AdventureWorks2012 database.
select PATINDEX('%MANSARD%',Clientname) from tblClientMaster
SELECT PATINDEX ( '%ein%', 'Das ist ein Test')
SELECT PATINDEX('%en_ure%', 'please ensure the door is locked')
Differents between STUFF and REPLACE in Sql Server
1.Select STUFF ('this is a test', 6,2, 'was')
o/p:-this was a test
2.Select REPLACE ('That is a test and it is successful!','is','was')
o/p:- That was a test and it was successful!
o/p:-this was a test
2.Select REPLACE ('That is a test and it is successful!','is','was')
o/p:- That was a test and it was successful!
Adding comma using STUFF in Sql Server
1.select distinct id,name,
STUFF((select ','+descrptn from test t1 where t2.id=t1.id for xml path('')),1,1,'') as description
from test t2
2.SELECT DISTINCT StateId, StateName
, STUFF((SELECT ','+City
FROM [StateProvince] S2
WHERE S1.StateId = S2.StateId
FOR XML PATH('')), 1, 1, '') AS City
FROM [StateProvince] S1
STUFF((select ','+descrptn from test t1 where t2.id=t1.id for xml path('')),1,1,'') as description
from test t2
2.SELECT DISTINCT StateId, StateName
, STUFF((SELECT ','+City
FROM [StateProvince] S2
WHERE S1.StateId = S2.StateId
FOR XML PATH('')), 1, 1, '') AS City
FROM [StateProvince] S1
How to get unique record in Sql Server
create table test(id int,name varchar(30),descrptn varchar(30))
1.(it contain duplicate records)
select * from test
--here this table(test1) only keep unique records
select distinct * into test1 from test
--here drop the table test
drop table test
--here rename the table test1 to test
sp_rename test1,test
OR
2.(it contain duplicate records)
select * from test
--here this table(test1) only keep unique records
select distinct * into test1 from test
select * from test1
--here delete all the records of table(test) test
truncate table test
select * from test
--here insert one whole table(test1) records into another table(test)
insert into test select * from test1
select * from test
-- then we can drop the table(test1)
drop table test1
OR
insert into test select * from test
3.(it contain duplicate records)
select * from test
--select whole query given below and exucute,we will get unique records
with cte as(
select id,name,descrptn,RN = ROW_NUMBER()OVER(PARTITION BY id ORDER BY id)
FROM test
)
DELETE FROM CTE WHERE RN > 1
1.(it contain duplicate records)
select * from test
--here this table(test1) only keep unique records
select distinct * into test1 from test
--here drop the table test
drop table test
--here rename the table test1 to test
sp_rename test1,test
OR
2.(it contain duplicate records)
select * from test
--here this table(test1) only keep unique records
select distinct * into test1 from test
select * from test1
--here delete all the records of table(test) test
truncate table test
select * from test
--here insert one whole table(test1) records into another table(test)
insert into test select * from test1
select * from test
-- then we can drop the table(test1)
drop table test1
OR
insert into test select * from test
3.(it contain duplicate records)
select * from test
--select whole query given below and exucute,we will get unique records
with cte as(
select id,name,descrptn,RN = ROW_NUMBER()OVER(PARTITION BY id ORDER BY id)
FROM test
)
DELETE FROM CTE WHERE RN > 1
Example of Pivot in Sql Server
SELECT ClientNo,isnull([1],0) [0-30],isnull([2],0) [31-60],isnull([3],0) [61-90],isnull([4],0) [>90],BrokerName,AsOfDate,UserName
From (Select Amount,ClientNo,DaysInGroup,BrokerName,AsOfDate,UserName FROM #tblPivot) a
PIVOT( sum(Amount)
FOR DaysInGroup IN ([1],[2],[3],[4])) AS PVTTable1
Ex:
Amount ClientNo DaysInGroup BrokerName AsOfDate UserName
16288.333 2 2 GUARDIAN INSURANCE BROKERS 2016-09-10 00:00:00.000 amtpl
479850.254 2 3 GUARDIAN INSURANCE BROKERS 2016-09-10 00:00:00.000 amtpl
Ans:
ClientNo 0-30 31-60 61-90 >90 BrokerName AsOfDate UserName
2 0.00 16288.333 479850.254 0.00 GUARDIAN INSURANCE BROKERS 2016-09-10 00:00:00.000 amtpl
From (Select Amount,ClientNo,DaysInGroup,BrokerName,AsOfDate,UserName FROM #tblPivot) a
PIVOT( sum(Amount)
FOR DaysInGroup IN ([1],[2],[3],[4])) AS PVTTable1
Ex:
Amount ClientNo DaysInGroup BrokerName AsOfDate UserName
16288.333 2 2 GUARDIAN INSURANCE BROKERS 2016-09-10 00:00:00.000 amtpl
479850.254 2 3 GUARDIAN INSURANCE BROKERS 2016-09-10 00:00:00.000 amtpl
Ans:
ClientNo 0-30 31-60 61-90 >90 BrokerName AsOfDate UserName
2 0.00 16288.333 479850.254 0.00 GUARDIAN INSURANCE BROKERS 2016-09-10 00:00:00.000 amtpl
Rename the Column Name in Sql Server
sp_RENAME 'tblWebClaimsBatch.TransactionDate' , 'Trans_Date', 'COLUMN'
Validating or Comparing between Two Dates-one from textbox-two from RaddatePicker
var txtSessionUID = document.getElementById('txtSessionUID')
var today = new Date();
var Year = today.getFullYear();
var Month = today.getMonth();
var Day = today.getDate();
var usetoDate = new Date(Year, Month, Day); // yyyy/mm/dd
var txtDate = document.getElementById('txtDate').value;
// var arrDate = txtDueDate.split("/");
// var useDate = new Date(arrDate[2], arrDate[1] - 1, arrDate[0]); // yyyy/mm/dd
var arrDate = txtDate.split("-");
var useDate = new Date(arrDate[0], arrDate[1] - 1, arrDate[2]); // yyyy/mm/dd
if (txtSessionUID.value != '') {
if (txtSessionUID.value == 13) {
if (useDate > usetoDate) {
alert("Date Should not Be Greater than to Today's Date..");
$find("txtDate").clear();
RPfFocus();
return false;
}
} else {
if (useDate > usetoDate) {
alert("Date Should not Be Greater than to Today's Date..");
$find("txtDate").clear();
RPfFocus();
return false;
}
if (useDate < usetoDate) {
alert("Date Should not Be Less than to Today's Date..");
$find("txtDate").clear();
RPfFocus();
return false;
}
}
}
}
}
var today = new Date();
var Year = today.getFullYear();
var Month = today.getMonth();
var Day = today.getDate();
var usetoDate = new Date(Year, Month, Day); // yyyy/mm/dd
var txtDate = document.getElementById('txtDate').value;
// var arrDate = txtDueDate.split("/");
// var useDate = new Date(arrDate[2], arrDate[1] - 1, arrDate[0]); // yyyy/mm/dd
var arrDate = txtDate.split("-");
var useDate = new Date(arrDate[0], arrDate[1] - 1, arrDate[2]); // yyyy/mm/dd
if (txtSessionUID.value != '') {
if (txtSessionUID.value == 13) {
if (useDate > usetoDate) {
alert("Date Should not Be Greater than to Today's Date..");
$find("txtDate").clear();
RPfFocus();
return false;
}
} else {
if (useDate > usetoDate) {
alert("Date Should not Be Greater than to Today's Date..");
$find("txtDate").clear();
RPfFocus();
return false;
}
if (useDate < usetoDate) {
alert("Date Should not Be Less than to Today's Date..");
$find("txtDate").clear();
RPfFocus();
return false;
}
}
}
}
}
Example of Java script validation using ASP.Net
--ddl validation
var ddlBusinessCat = document.getElementById('ddlBusinessCat').value;
if (ddlBusinessCat == '') {
alert('Select Business Category');
document.getElementById('ddlBusinessCat').focus();
return false;
}
--telerik ddl validation
var ddlCurrency = document.getElementById('ddlCurrency').value;
if (ddlCurrency == '') {
alert('Select Currency');
//document.getElementById('ddlCurrency').focus();
var comboBox = $find('ddlCurrency');
var input = comboBox.get_inputDomElement();
input.focus();
return false;
}
--listbox Validation
var lstRomType = document.getElementById('lstRomType').value;
if (lstRomType == '') {
alert('Select Room Type');
document.getElementById('lstRomType').focus();
return false;
}
--RaddatePicker Validation--No Focus
var txtEffectiveFrom = document.getElementById('txtEffectiveFrom');
if (txtEffectiveFrom.value == '') {
alert("Enter the Effective From Date")
$find("txtEffectiveFrom ").clear();
RPfFocus();
return false;
}
-----------
<div>
<script language="javascript" type="text/javascript">
function RPfFocus() {
var picker = $find("<%= txtDate.ClientID %>");
picker.showPopup();
}
</div>
-----------
--set date to RaddatePicker
datepicker.set_selectedDate('2005-08-06 00:00:00.000');
--Clear to RaddatePicker
$find('txtDate').clear();
--Enabled to RaddatePicker
$find("txtDate").set_enabled(true);
-----------
--Assigning/Changing Label Name in inline Page
document.form1.txtBank.disabled = false;
document.form1.txtAcNo.disabled = false;
document.form1.txtChequeNo.disabled = false;
document.getElementById('txtBank').style.backgroundColor = "white";
document.getElementById('txtAcNo').style.backgroundColor = "white";
document.getElementById('txtChequeNo').style.backgroundColor = "white";
document.getElementById('lblChequeNo').innerText = "ChequeNo";
document.getElementById('lblAcNo').innerText = "A/C No";
$find('txtDate').clear();
$find("txtDate").set_enabled(true);
RPfFocus();
var ddlBusinessCat = document.getElementById('ddlBusinessCat').value;
if (ddlBusinessCat == '') {
alert('Select Business Category');
document.getElementById('ddlBusinessCat').focus();
return false;
}
--telerik ddl validation
var ddlCurrency = document.getElementById('ddlCurrency').value;
if (ddlCurrency == '') {
alert('Select Currency');
//document.getElementById('ddlCurrency').focus();
var comboBox = $find('ddlCurrency');
var input = comboBox.get_inputDomElement();
input.focus();
return false;
}
--listbox Validation
var lstRomType = document.getElementById('lstRomType').value;
if (lstRomType == '') {
alert('Select Room Type');
document.getElementById('lstRomType').focus();
return false;
}
--RaddatePicker Validation--No Focus
var txtEffectiveFrom = document.getElementById('txtEffectiveFrom');
if (txtEffectiveFrom.value == '') {
alert("Enter the Effective From Date")
$find("txtEffectiveFrom ").clear();
RPfFocus();
return false;
}
-----------
<div>
<script language="javascript" type="text/javascript">
function RPfFocus() {
var picker = $find("<%= txtDate.ClientID %>");
picker.showPopup();
}
</div>
-----------
--set date to RaddatePicker
datepicker.set_selectedDate('2005-08-06 00:00:00.000');
--Clear to RaddatePicker
$find('txtDate').clear();
--Enabled to RaddatePicker
$find("txtDate").set_enabled(true);
-----------
--Assigning/Changing Label Name in inline Page
document.form1.txtBank.disabled = false;
document.form1.txtAcNo.disabled = false;
document.form1.txtChequeNo.disabled = false;
document.getElementById('txtBank').style.backgroundColor = "white";
document.getElementById('txtAcNo').style.backgroundColor = "white";
document.getElementById('txtChequeNo').style.backgroundColor = "white";
document.getElementById('lblChequeNo').innerText = "ChequeNo";
document.getElementById('lblAcNo').innerText = "A/C No";
$find('txtDate').clear();
$find("txtDate").set_enabled(true);
RPfFocus();
To get dependent SP's name in which the SP/Table is using_in Sql Server
1.To get dependent SP's name in which the table is using.(means-table's used by which SP's)
SELECT DISTINCT so.name
FROM syscomments sc
INNER JOIN sysobjects so ON sc.id=so.id
WHERE sc.TEXT LIKE '%occ_order_approvals%'
2.To get dependent SP's name in which the SP is using.(means-SP used by which SP's)
sp_whereiscolumn 'SP_ORDER_GEN_NUM'
3.Get SP names by any related text names
SELECT name
FROM sys.procedures
WHERE Object_definition(object_id) LIKE '%deletecandidatefromcloud%'
4.For performance issue...run below SP
exec sp_updatestats
SELECT DISTINCT so.name
FROM syscomments sc
INNER JOIN sysobjects so ON sc.id=so.id
WHERE sc.TEXT LIKE '%occ_order_approvals%'
2.To get dependent SP's name in which the SP is using.(means-SP used by which SP's)
sp_whereiscolumn 'SP_ORDER_GEN_NUM'
3.Get SP names by any related text names
SELECT name
FROM sys.procedures
WHERE Object_definition(object_id) LIKE '%deletecandidatefromcloud%'
4.For performance issue...run below SP
exec sp_updatestats
Write a function to split comma's in Sql Server
Drop function dbo.SplitingCommas
Go
Create function dbo.SplitingCommas(@String nvarchar(4000), @Delimiter char(1))
Returns @Results Table (Id int identity(1,1),Items nvarchar(4000))
As
Begin
Declare @Index int
Declare @Slice nvarchar(4000)
Select @Index = 1
If @String Is NULL Return
While @Index != 0
Begin
Select @Index = CharIndex(@Delimiter, @String)
If @Index != 0
Select @Slice = left(@String, @Index - 1)
else
Select @Slice = @String
Insert into @Results(Items) Values (@Slice)
Select @String = right(@String, Len(@String) - @Index)
If Len(@String) = 0 break
End
Return
End
Go
Create function dbo.SplitingCommas(@String nvarchar(4000), @Delimiter char(1))
Returns @Results Table (Id int identity(1,1),Items nvarchar(4000))
As
Begin
Declare @Index int
Declare @Slice nvarchar(4000)
Select @Index = 1
If @String Is NULL Return
While @Index != 0
Begin
Select @Index = CharIndex(@Delimiter, @String)
If @Index != 0
Select @Slice = left(@String, @Index - 1)
else
Select @Slice = @String
Insert into @Results(Items) Values (@Slice)
Select @String = right(@String, Len(@String) - @Index)
If Len(@String) = 0 break
End
Return
End
Numeric with only one dot allowed to textbox in ASP.Net
<script type="text/javascript" language="javascript">
function validatetxtbx(val) {
var e = event || evt; // for trans-browser compatibility
var charCode = e.which || e.keyCode;
// for only numeric and dot allowed
if (!(charCode == 46 || (charCode >= 48 && charCode <= 57))) {
alert("Only Numeric & Decimal values allowed.");
return false;
}
//for press char value
var curchar = String.fromCharCode(charCode);
//concate previous value with current press value
var mainstring = val + curchar;
if (mainstring.indexOf('.') > -1) {
if (mainstring.split('.').length > 2) {
alert("Only one dot allowed.");
return false;
}
}
//alert("hi")
}
</script>
and then add below one in code behind at Page_Load()
function validatetxtbx(val) {
var e = event || evt; // for trans-browser compatibility
var charCode = e.which || e.keyCode;
// for only numeric and dot allowed
if (!(charCode == 46 || (charCode >= 48 && charCode <= 57))) {
alert("Only Numeric & Decimal values allowed.");
return false;
}
//for press char value
var curchar = String.fromCharCode(charCode);
//concate previous value with current press value
var mainstring = val + curchar;
if (mainstring.indexOf('.') > -1) {
if (mainstring.split('.').length > 2) {
alert("Only one dot allowed.");
return false;
}
}
//alert("hi")
}
</script>
and then add below one in code behind at Page_Load()
TextBox1.Attributes.Add("onfocus","validatetxtbx()");
MsgBox and ConfirmationBox Example in ASP.Net
1.Confirmation Box-JS
<asp:Button CssClass="srsbutton" ID="btnActivate" Text="Active" runat="server" Width="120px" Visible="false" OnClientClick="return confirmation();"/>
<script type="text/javascript">
function confirmation() {
if (confirm('Are you sure you want to Inacive ?')) {
return true;
} else {
return false;
}
}
</script>
2.VB.Net-Code Behind
If MsgBox("Prompt", "Are you sure you want to Inactive ?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
InActivePostDelete()
End If
3.VB.Net-Code Behind
Dim resultResponse = MsgBox("Are you sure you want to add/remove students of new order?", MsgBoxStyle.YesNo, "Prompt")
If resultResponse = MsgBoxResult.Yes Then
Page.RegisterClientScriptBlock("ChildInfo", "<script type='text/javascript'>window.open('frmChildInfo.aspx?qOrderId=" & Request.QueryString("NewOrderId") & "','_blank','width=1200,height=600,top=50px,left=100px,scrollbars=no,status=yes,resizable=false');</script>")
End If
4.using JS and call from Code Behind using Ajax ScriptManager
-----In frmViewOrder.aspx
<script type="text/javascript">
function fnConfirmARChild(NewOrderId) {
var x;
x = confirm('Are you sure you want to add/remove students of new order?')
if (x == true) {
window.open('frmChildInfo.aspx?qOrderId=' + NewOrderId, '_blank', 'width=1200,height=600,top=50px,left=100px,scrollbars=no,status=yes,resizable=false');
}
else {
return false;
}
}
</script>
-----In frmViewOrder.aspx.vb
Me.Page.RegisterStartupScript("confirm", "<script type='text/javascript'>fnConfirmARChild('" & Request.QueryString("NewOrderId") & "');</script>")
5.Show Confirm Box from GridView by setting value to HiddenField
-----frmChildInfo.aspx
<asp:HiddenField ID="hdnReturnDeleteValue" runat="server" />
<asp:Button ID="btnDeleteChild" runat="server" Text="Delete" CommandName="DeleteChild" OnClientClick="fnConfirmARChild()" CommandArgument='<%# Convert.ToString(Eval("Child_Id")) + "," + Convert.ToString(Eval("Order_Id")) %>' /></td>
<script type="text/javascript">
function fnConfirmARChild() {
var x;
x = confirm('Are you sure you want delete student from this order?')
document.getElementById('hdnReturnDeleteValue').value = false;
if (x == true) {
document.getElementById('hdnReturnDeleteValue').value = true;
return true;
}
else {
document.getElementById('hdnReturnDeleteValue').value = false;
return false;
}
</script>
-----frmChildInfo.aspx.vb
If hdnReturnDeleteValue.Value = "true" Then
ciSqlString = "uspDelete_OrderChildInfo"
SqlHelper.ExecuteNonQuery(ciSqlConnection, CommandType.StoredProcedure, ciSqlString, ciSqlParameter)
Me.Page.ClientScript.RegisterStartupScript(Me.GetType, "alert", "alert('Child Info deleted successfully.');", True)
BindChildInfoGrid()
End If
<asp:Button CssClass="srsbutton" ID="btnActivate" Text="Active" runat="server" Width="120px" Visible="false" OnClientClick="return confirmation();"/>
<script type="text/javascript">
function confirmation() {
if (confirm('Are you sure you want to Inacive ?')) {
return true;
} else {
return false;
}
}
</script>
2.VB.Net-Code Behind
If MsgBox("Prompt", "Are you sure you want to Inactive ?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
InActivePostDelete()
End If
3.VB.Net-Code Behind
Dim resultResponse = MsgBox("Are you sure you want to add/remove students of new order?", MsgBoxStyle.YesNo, "Prompt")
If resultResponse = MsgBoxResult.Yes Then
Page.RegisterClientScriptBlock("ChildInfo", "<script type='text/javascript'>window.open('frmChildInfo.aspx?qOrderId=" & Request.QueryString("NewOrderId") & "','_blank','width=1200,height=600,top=50px,left=100px,scrollbars=no,status=yes,resizable=false');</script>")
End If
4.using JS and call from Code Behind using Ajax ScriptManager
-----In frmViewOrder.aspx
<script type="text/javascript">
function fnConfirmARChild(NewOrderId) {
var x;
x = confirm('Are you sure you want to add/remove students of new order?')
if (x == true) {
window.open('frmChildInfo.aspx?qOrderId=' + NewOrderId, '_blank', 'width=1200,height=600,top=50px,left=100px,scrollbars=no,status=yes,resizable=false');
}
else {
return false;
}
}
</script>
-----In frmViewOrder.aspx.vb
Me.Page.RegisterStartupScript("confirm", "<script type='text/javascript'>fnConfirmARChild('" & Request.QueryString("NewOrderId") & "');</script>")
5.Show Confirm Box from GridView by setting value to HiddenField
-----frmChildInfo.aspx
<asp:HiddenField ID="hdnReturnDeleteValue" runat="server" />
<asp:Button ID="btnDeleteChild" runat="server" Text="Delete" CommandName="DeleteChild" OnClientClick="fnConfirmARChild()" CommandArgument='<%# Convert.ToString(Eval("Child_Id")) + "," + Convert.ToString(Eval("Order_Id")) %>' /></td>
<script type="text/javascript">
function fnConfirmARChild() {
var x;
x = confirm('Are you sure you want delete student from this order?')
document.getElementById('hdnReturnDeleteValue').value = false;
if (x == true) {
document.getElementById('hdnReturnDeleteValue').value = true;
return true;
}
else {
document.getElementById('hdnReturnDeleteValue').value = false;
return false;
}
</script>
-----frmChildInfo.aspx.vb
If hdnReturnDeleteValue.Value = "true" Then
ciSqlString = "uspDelete_OrderChildInfo"
SqlHelper.ExecuteNonQuery(ciSqlConnection, CommandType.StoredProcedure, ciSqlString, ciSqlParameter)
Me.Page.ClientScript.RegisterStartupScript(Me.GetType, "alert", "alert('Child Info deleted successfully.');", True)
BindChildInfoGrid()
End If
Hide GridView Column using CSS in .Net
<style type="text/css">
.hiddencol
{
display: none;
}
</style>
<asp:BoundField DataField="EMail" HeaderText="EMail" HeaderStyle-CssClass="hiddencol" ItemStyle-CssClass="hiddencol" />
.hiddencol
{
display: none;
}
</style>
<asp:BoundField DataField="EMail" HeaderText="EMail" HeaderStyle-CssClass="hiddencol" ItemStyle-CssClass="hiddencol" />
Execute Stored Procedure with OUT PUT Parameter in SQL Server
1.declare @new_waiver_id int
exec uspInsert_Cwadoesp_waiver_requests 875118,0,2,0,1,0,0,0,0,0,0,'New York City Prevailing Wage Law : Pay rate is below required minimum pay rate for the position.',@new_waiver_id output
select @new_waiver_id as new_waiver_id
2.declare @temp_reg_hrs float ,@temp_ot_hrs float
exec tpweb_cwa_doe_get_order_total_hours 7,7,7,7,7,0,0,'09/16/2017','09/16/2017',@temp_reg_hrs output,@temp_ot_hrs output
select '@temp_reg_hrs'=@temp_reg_hrs,'@temp_ot_hrs'=@temp_ot_hrs
exec uspInsert_Cwadoesp_waiver_requests 875118,0,2,0,1,0,0,0,0,0,0,'New York City Prevailing Wage Law : Pay rate is below required minimum pay rate for the position.',@new_waiver_id output
select @new_waiver_id as new_waiver_id
2.declare @temp_reg_hrs float ,@temp_ot_hrs float
exec tpweb_cwa_doe_get_order_total_hours 7,7,7,7,7,0,0,'09/16/2017','09/16/2017',@temp_reg_hrs output,@temp_ot_hrs output
select '@temp_reg_hrs'=@temp_reg_hrs,'@temp_ot_hrs'=@temp_ot_hrs
Exception Handling using ajax jquery client side script
1.$.post(url, { model: dataModel ,weekending:weekending})
.done(function (data) {
if (data != "") {
$("#ConfictTimeSlip").val(data.ConfictTimeSlip);
if (data.ConfictTimeSlip > 0) {
$("#lblPopupmessage").html("The hours you have entered above conflict with a time slip that already exists in the our system.<br/>Duplicate time slips are not allowed!").css('color', 'red');
$('#btnCorrect').prop('disabled', true);
}
else{$('#btnCorrect').prop('disabled', false);}
}
})
.fail(handleAjaxError)
2.$.ajax({
type: "GET",
url: url,
success: function (data) { $("#tblBindPersonalJobBank").html(data); },
error: handleAjaxError
});
.done(function (data) {
if (data != "") {
$("#ConfictTimeSlip").val(data.ConfictTimeSlip);
if (data.ConfictTimeSlip > 0) {
$("#lblPopupmessage").html("The hours you have entered above conflict with a time slip that already exists in the our system.<br/>Duplicate time slips are not allowed!").css('color', 'red');
$('#btnCorrect').prop('disabled', true);
}
else{$('#btnCorrect').prop('disabled', false);}
}
})
.fail(handleAjaxError)
2.$.ajax({
type: "GET",
url: url,
success: function (data) { $("#tblBindPersonalJobBank").html(data); },
error: handleAjaxError
});
Example of Table variable in Sql Server
1.Creating Table Variable:
DECLARE @Posted_Split TABLE (
Post_Site INT
,Post_Type TINYINT
)
2.Inserting data into Table Variable:
INSERT INTO @Posted_Split
select 2,0
3.To view data of Table Variable:
select Post_Site,Post_Type from @Posted_Split
4.Joining with Table Variable:
UPDATE tblJobPostData set JobPost_ID=450,Post_Type=PS.Post_Type,Post_Site=PS.Post_Site,IsProcessed=0
from tblJobPostData JP inner join @Posted_Split PS on PS.Post_Type=JP.Post_Type and PS.Post_Site=JP.Post_Site
where JP.jobpost_id=450
DECLARE @Posted_Split TABLE (
Post_Site INT
,Post_Type TINYINT
)
2.Inserting data into Table Variable:
INSERT INTO @Posted_Split
select 2,0
3.To view data of Table Variable:
select Post_Site,Post_Type from @Posted_Split
4.Joining with Table Variable:
UPDATE tblJobPostData set JobPost_ID=450,Post_Type=PS.Post_Type,Post_Site=PS.Post_Site,IsProcessed=0
from tblJobPostData JP inner join @Posted_Split PS on PS.Post_Type=JP.Post_Type and PS.Post_Site=JP.Post_Site
where JP.jobpost_id=450
Subscribe to:
Posts (Atom)