Posts

SQL – Generate decimal numbers sequence for particular number range

Image
Friends, Sometimes we need mathematical assistance in SQL for such queries. Same here, it helps me to find challenging in all the way. Some of my friends helps me out to crack the records for my query, Here I am sharing simple solution for this, ;WITH cte      AS (SELECT Cast(-77 AS NUMERIC(22, 3)) AS num –Min value from your data          UNION ALL          SELECT Cast(num + 0.00001 AS NUMERIC(22, 5))          FROM   cte          WHERE  num < Cast(89 AS NUMERIC(22, 5))) — Max value from your data SELECT * FROM   cte OPTION (maxrecursion 0)  Try it 

SQL Server - string_split function

In SQL Server 2016, some new functions arrived. One of them will be “ string_split “. It helps to split string without writing code. Syntax –   string_split (<string>,<separator>) Example – SELECT * FROM STRING_SPLIT(‘NIHAR BHALCHANDRA KULKARNI’,’ ‘) Output – Value ————- NIHAR BHALCHANDRA KULKARNI This is how string split into separate characters and rows.

Dynamic Query in SQL Server

Sometimes we need to modify query based on different condition , scenarios etc. To avoid such long length and repeated code , we build dynamic query. Here output same as normal query execution. Syntax - declare @var1 varchar(max) or nvarchar(max) Select @var1 = N'<query to be written>' Exec <default sp name> @var1 Following points need to consider for writing dynamic query : 1.  Combination of methods and declaration   Suppose we are declare in following way as - declare @var varchar(max) select @var = N'select * from datUsers' select @var execute sp_executesql @var Here error occur as Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'. Follow below combination based on variable datatypes 1.  using VARCHAR - declare @var varchar(max) select @var = N'select * from datUsers' select @var execute(@var) OUTPUT - (1 row(s) affected) 2.  using NVARCHAR - declare @var1 nvarchar(max) sel...

SQL SERVER – Using PowerShell and Native Client to run queries in SQL Server

Image
Many time I heard about Powershell , but never go thorogh it. I tried it at basic level to connect to sql server from SQL Native Client. Coding looks similar to web developers  (like some properties as  'ExecuteScalar' ,'ExecuteNonQuery' ). Its very interesting which comes with SSMS (SQL Server Management Studio) . I already have sample database created on my local , which I would like to connect through powershell. /*Create table and keep some records for fetching from SQL Query*/ CREATE TABLE [dbo].[tbl_Employee](  [ID] [int] IDENTITY(1,1) NOT NULL,  [FirstName] [varchar](max) NULL,  [LastName] [varchar](max) NULL,  [Address] [varchar](max) NULL)   "1" indicates record inserted successfully !!    PowerShell very useful any kind of deployment on remote servers  .   Share your comments with addition information . Hope u will try it . You might get few error , but its interesting.

Ways to SELECT XML string using Nodes and OPENXML()

XML reading is most probably way of reading data from file. Only for knowledge we are checking performance by two ways OPENXML() and Nodes(). Check following the queries at your end as part of "Performace Tuning ". OpenXML() -                       OpenXML() is a rowset provider. OpenXML can be used in T-SQL statements in which rowset providers such as a table, view, or the OPENROWSET function can appear. Example : DECLARE @idoc int , @doc varchar ( 1000 ), @XMLString xml SET @doc = ' <ROOT> <Customer CustomerID="1" ContactName="Nihar"> <Order CustomerID="1" EmployeeID="5" OrderDate="1996-07-04T00:00:00"> <OrderDetail ProductID="11" Quantity="12"/> <OrderDetail ProductID="42" Quantity="10"/> </Order> </Customer> <Customer CustomerID="2" ContactName="HR"> <Order CustomerID=...

Error Message Severity Levels in SQL Server

Sample Code: BEGIN TRY     SELECT 1/0; END TRY BEGIN CATCH     SELECT ERROR_SEVERITY() AS ErrorSeverity; END CATCH; GO Output : 16 ############################################################### Here we didnt understand what exactly severity occurs in SQL Expression Find descriptions here for each severity level. Severity Levels 0 through 19 : Error messages with a severity level of 10 are informational. Error messages with severity levels from 11 through 16 are generated by the user and can be corrected by the user. Severity levels from 17 and 18 are generated by resource or system errors; the user's session is not interrupted. Severity Level 10: Status Information This is an informational message that indicates a problem caused by mistakes in the information the user has entered. Severity level 0 is not visible in SQL Server. Severity Levels 11 through 16 These messages indicate errors that can be corrected by the user. Severity Le...

Fix a Problem with Aliasing

We are aware of aliasing in SQL Server , but its impact is huge. You are presented with another grouped query that fails, this time because of an aliasing problem. As in the first exercise, you are provided with instructions on how to fix the query.               1. Clear the query window, type the following query, and execute it.                                    SELECT OrgID, SUM(SaleOrders) AS SaleOrders                    FROM Sales.Orders                    WHERE  SaleOrders > 20000              ...

Show animated wait window ,while processing request

Its a major problem faced while processing DB request else functions etc . The problem is when we perform command on database it takes time of few seconds, at that time my applications main window becomes halted. when i performs command on database execution returns on main application when whole command is executed on database. Just Like "NonQuery()" Lets assume we are working on asp.net 4.0 and sending request to view.  i am showing a form before it and closing that form after the command, but problem is i am putting a GIF image on the form, because exection is halted on main application, the gif don't shows animation until the command is executed. so that i putted it on a BackGroundWorker, but main thread is halted so its child tread also become halt. we can not put database transaction in background worker, becuase sometime working is depended on result retrieved from database, and we want to halt application untill data is not fetched, but in this case ...

Dynamic query in SQL

Dynamic query which nothing but conditional query which help to optimize query and improve performance of query. Currently using   [AdventureWorksLT2008R2] datbase as following : Try first EXEC ('SELECT * FROM SalesLT.Product') You can try following just for idea DECLARE @SQL NVARCHAR(max), @ParmDefinition NVARCHAR(1024) DECLARE @ListPrice money = 2000.0, @LastProduct varchar(64) SET @SQL =       N'SELECT @pLastProduct = max(Name)                    FROM SalesLT.Product                    WHERE ListPrice >= @param1' SET @ParmDefinition = N'@param1 money,                         @pLastProduct varchar(64) OUTPUT' EXECUTE sp_executeSQL      -- Dynamic T-SQL             @SQL,             @ParmDefin...

Paging in SQL Server

Image
Paging is one the functionality which we can achieved in many ways. So many plugins,technologies used for development. My sir already used in 2008, I think over to tried it in by different way. It found that Microsoft provides pagination feature with SQL Server 2012. We can acheived it by row_number() and minimum ids etc But from SQL Server 2012 we can do pagination by using FETCH and OFFSET. From above records, I need to split next 6 records after 32 Address ID. So doing pagination is a two-step process: - First mark the start of the row by using “OFFSET” command. Second specify how many rows you want to fetch by using “FETCH” command. Query :  1. Fetching records from 0 to above SELECT * FROM [Address]  order by AddressID offset 0 rows – start from zero Fetch Next 6 Rows only 2. Fetching records from 32 to next 6 records paging. SELECT * FROM [Address]  order by AddressID offset 6 rows  Fetch Next 6 Rows only [...

NIHAR'S BLOG: Sequence : Auto Generated ID's in SQL Server 2012

NIHAR'S BLOG: Sequence : Auto Generated ID's in SQL Server 2012 : Hi friends , after long time come back with new excellent features of SQL Server 2012. Don't worry , I am not posting all features bec...

Reading text file in SQL Server

There are many option to read text file data and store it into database. We may have following options available for reading/storing/updating data into database 1.  Import and Export wizard of SQL Serve 2. SQL Server Integration Services 3. Using C# with SQL CLR will insert data into tables But , using few lines code of query need to execute in SSMS. SQL Server provides  " BULK INSERT "  Operation to read data from local system and store it into database tables. Steps : 1. First create text file with some name "Abc.txt" and enter values as nihar, Vishal, Vivek, Save and Copy path of file. 2. Open SSMS and create temp table for data insertion Create table temp_Data ( name nvarchar(20) ) 3.  Use following query to view operation BULK INSERT  Temp_data FROM   'D:\Abc.txt' WITH ( FIELDTERMINATOR  = ',' ,     -- Here you can use any delimiter for seperation ROWTERMINATOR  = '\n'   ); SELECT * FROM ...