When called multiple times in a single batch, rand() returns the same number. So it is better to use convert(varbinary,newid()) as the seed argument: SELECT 1.0 + floor(110 * RAND(convert(varbinary, newid()))) AS random_number newid() is guaranteed to return a different value each time it’s called, even within the same batch, so using it as a seed […]
Category: SQL
How to Find Day Name From Date in SQL Server
There are two methods to find a day name from a date in SQL Server: DATENAME() Function FORMAT() Function Using DATENAME DECLARE @Date DATE = ‘2024-07-27’; SELECT @Date As [TDate], DATENAME(WEEKDAY, @Date) AS [Day_Name]; Using FORMAT DECLARE @Date DATE = ‘2024-07-27’; SELECT @Date As [TDate], FORMAT(@Date, ‘dddd’) AS [Day_Name]
How to make pagination in MS SQL Server
In MS SQL Server, we can achieve the pagination functionality by using OFFSET and FETCH clauses with ORDER BY in a SELECT statement. OFFSET: Represents the number of rows to be skipped from the result set. It should be 0 or greater than 0. FETCH: Represents the number of rows to be displayed in the result. Notes: ORDER BY is mandatory for the use OFFSET […]
How to update Identity Column in SQL Server
— Set Identity insert on so that value can be inserted into this column SET IDENTITY_INSERT YourTable ON GO — Insert the record which you want to update with new value in the identity column INSERT INTO YourTable(IdentityCol, otherCol) VALUES(5, ‘myValue’) GO — Delete the old row of which you have inserted a copy (above) […]
How to check seed value of tables in SQL
–View the current value: DBCC CHECKIDENT (“{table name}”, NORESEED) –Set it to the max value plus one: DBCC CHECKIDENT (“{table name}”, RESEED) –Set it to a spcefic value: DBCC CHECKIDENT (“{table name}”, RESEED, {New Seed Value})
How to find a specific text string in a SQL Server Stored Procedure, Function, View or Trigger
— Applicable for SQL 2005 and later versions USE [Your_DB]; SELECT [Scehma] = schema_name(o.schema_id), o.Name, o.type FROM sys.sql_modules m INNER JOIN sys.objects o ON o.object_id = m.object_id WHERE m.definition like ‘%your_text_to_search%’
How to get the first and the last day of previous month in SQL Server
SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0) –First day of previous month SELECT DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1) –Last Day of previous month
Not Null check on LEFT function with T-SQL
CONCAT function ignores NULLs: SELECT CONCAT(LEFT(LastName, 1), ‘,’ , LEFT(FirstName, 1), ‘ ‘ + LEFT(MiddleName, 1)) theNameWithInitials FROM myTable If you use CONCAT, you will not need to worry about whether LEFT(X) is null or not.
How to insert results of a stored procedure into a temporary table
CREATE TABLE #tmpTable ( COL1 int, COL2 int, COL3 nvarchar(max), COL4 nvarchar(max), COL5 bit ) INSERT INTO #tmpTable exec SpGetRecords ‘Params’ NOTE: The columns of #tmpTable must be the same as SpGetRecords. Otherwise, there will be a problem. If there are no parameters in the stored procedure, you don’t need to use ‘Params’.
How to use OUTPUT for Insert, Update and Delete in SQL
The OUTPUT clause was introduced in SQL Server 2005. The OUTPUT clause returns the values of each row that was affected by an INSERT, UPDATE, or DELETE statement. It even supports a MERGE statement, which was introduced in SQL Server 2008 version. The OUTPUT clause has access to two temporary or in-memory SQL tables, INSERTED […]
How to get the first and last date of the current year in SQL
SELECT DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0) AS StartOfYear, DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, -1) AS LastDayOfYear, DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, 0) AS FirstOfNextYear, DATEADD(ms, -3, DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, 0)) AS LastTimeOfYear Thanks to Jamie F for the answer.
How to get difference between 2 tables in MSSQL
If you have two tables A and B, both with column C, here are the records, which are present in the table A but not in B: SELECT A.* FROM A LEFT JOIN B ON (A.C = B.C) WHERE B.C IS NULL To get all the differences with a single query, a full join must be used, like this: […]
How to solve the stucking on “Loading Packages” phase for SSMS installation
to fix this problem: remove temp files from %temp% folder (C:\Users<user name>\AppData\Local\Temp) open the register and remove “HKLM\SOFTWARE\WOW6432Node\Microsoft\Microsoft SQL Server Management Studio” or execute via cmd (with admin rights): reg DELETE “HKLM\SOFTWARE\WOW6432Node\Microsoft\Microsoft SQL Server Management Studio” /reg:32 run install with admin rights NOTE: Just for those who don’t know register just open CMD as an […]
How to reset identity seed after deleting records in SQL
The DBCC CHECKIDENT management command is used to reset the identity counter. The command syntax is: DBCC CHECKIDENT (table_name [, { NORESEED | { RESEED [, new_reseed_value ]}}]) [ WITH NO_INFOMSGS ] Example: DBCC CHECKIDENT (‘[TestTable]’, RESEED, 0); IMPORTANT: The following example forces the current identity value in the AddressTypeID column in the AddressType table to a value […]
How to create a single string from multiple rows in T-SQL and MySQL
To create a single string from multiple rows in MySQL, you can use the GROUP_CONCAT function. This function allows you to concatenate values from multiple rows into a single string, separated by a specified delimiter. Here is an example of how you can use this function: SELECT GROUP_CONCAT(column_name ORDER BY column_name ASC SEPARATOR ‘,’) FROM […]
SQL Tip: “@@IDENTITY” should not be used
@@IDENTITY returns the last identity column value created on a connection, regardless of the scope. That means it could return the last identity value you produced, or it could return a value generated by a user-defined function or trigger, possibly one fired because of your insert. In order to access the last identity value created […]
SQL Tip: “NOCOUNT” should be activated on “PROCEDURE” and “TRIGGER” definitions
NOCOUNT is by default deactivated (OFF) at the server level. It means by default, the server will send to the client the number of rows affected by the SQL query executed which is, in most cases, useless because no one will read this information. Deactivating this feature will save some network traffic and improve the […]
SQL Tip: “NULL” should not be compared directly
“NULL” is never equal to anything, even itself. Therefore comparisons using equality operators will always return False, even when the value actually IS NULL. For that reason, comparison operators should never be used to make comparisons with NULL; IS NULL and IS NOT NULL should be used instead. Bad example: UPDATE books SET title = ‘unknown’ WHERE title = NULL — Noncompliant […]