You need to declare a table variable with the same shape as the TVF result, then use INSERT INTO not SELECT INTO, and remember to add brackets/parentheses to the end of the function name when invoking it, i.e. Foo() not just Foo:
DECLARE @Table TABLE (
[Id] [int] NULL,
[Number] [int] NOT NULL,
[Name] [nvarchar](255) NULL,
... dozens of ...
Probably you're moving the row when you set Deleted=1 and reading it again with your FAST_FORWARD cursor. Use a STATIC cursor instead, which will iterate a copy of the data, and avoid mutating the data structure you are traversing.
DECLARE st CURSOR LOCAL STATIC FOR . . .
You want WHILE @@FETCH_STATUS = 0 which means continue unless something isn't right.
Using <> -1 means it will continue even if the row fetched was missing, or it's not performing a fetch operation, making it infinite unless you get -1 as a return value, since there are 4 return values for @@FETCH_STATUS.
0 The FETCH statement was successful.
Thnaks, it has helped a lot. There is a small bug as the Duration is not in Seconds it is in HHMMSS
I have fix it this way:
, x.end_time AS end_time
, datediff(minute, x.start_time, x.end_time) AS Duration
SELECT DISTINCT --TOP 100 PERCENT
cast([sJOB].[job_id] AS VARCHAR(max)) AS execution_id
Here's a timeline of the events you described, as well as my commentary on what was the likely cause of your bad plan.
You're alerted of a slow query that was previously fast
Bad times, I empathize!
You go crazy and run "the forbidden dbcc freeproccache" and it doesn't help
Usually, clearing the cache fixes problems like this if the problem is parameter ...
This can be due to the maximum amount of characters that the result to grid can return, 65535.
Starting from SSMS 18.2 you are able to change this.
Thanks Aaron Bertrand for pointing that out.
Aaron also mentions:
if 64kb is the limit you’re hitting, there are a lot of places where
statement text is truncated long before that any way (see literally
You can merge the data spread across the three columns by using a CASE switch.
I have an example to share but, without detail about the data you are storing in the Employed, Non-Employed, and Retired columns I am guessing at a few things. If you can update your question with more detail about the type of data store in those columns then it will help guide ...
As pointed out by @SQLRaptor in a comment, you're running this code against an empty table. In fact, it's a table variable, which can only contain rows while the code is running.
The following example shows that your code works if rows are inserted into the table:
DECLARE @Table TABLE (Col1 int, Col2 datetime);
INSERT INTO @Table (Col1, Col2)
VALUES (1, '...
For what it's worth, this behaviour changes in SQL Server 2016. When I try against 2017 with COMPATIBILITY_LEVEL = 120 I see your observed behaviour. When COMPATIBILITY_LEVEL = 130 both input values produce the same rounded output value 9.77.
There is some documentation here but it is not conclusive. I do not have 2014 documentation to hand but it would be ...
The best solution would be to ditch the RR (or RRRR) notation completely. It was meant as a short-term, kick the can down the road, fix to buy some time remediating for Y2k. That was TWENTY YEARS ago. Long, long past time to wean ourselves it and simply start using 4-digit years in everything we do.
Randi's answer works perfectly, and Akina's is much tidier if you are on SQL Server 2017 or better, but on older versions you can do this with slightly less code and fewer operations like reverse/stuff. Given this data:
CREATE TABLE #temp(col varchar(255));
SELECT 'foo' UNION ALL SELECT '"bar"'
UNION ALL SELECT 'blat"' UNION ALL ...
You could try something like this
SELECT CASE WHEN RIGHT(fieldname,1) = '"' AND LEFT(fieldname,1) = '"' THEN REVERSE(STUFF(REVERSE(STUFF(fieldname, 1, 1, '')), 1, 1, ''))
WHEN RIGHT(fieldname,1) = '"' THEN REVERSE(STUFF(REVERSE(fieldname), 1, 1, ''))
WHEN LEFT(fieldname,1) = '"' THEN STUFF(fieldname, 1, 1, '')
ELSE fieldname END as ...
Is there a way to express RR in T-SQL?
It can be done, for example, as
-- from date to string
SELECT FORMAT(datetime_field, CASE WHEN YEAR(datetimefield) > 49
END) AS date_formatted_as_RR, ...
if ID and ID2 columns are key columns then you need to worry about that faulty Update Statement.
Agree, those values aren't being changed but it create very expensive Query Plan.
In Fact you should Compare the query Plan with and without mt.col1 = s.col1
, mt.col2 = s.col2 in Update your Self.
SET mt.col1 = s.col1
SQL server may choose to perform an in-place update or an insert and a delete depending on many factors and you shouldn’t worry about it.
Since the keys are not being updated I would leave them out of the SET clause to help the optimizer make the best decision.
If you are using SQL Server 2008 or later, look at the MERGE statement which can replace both ...
From error message,
Arithmetic overflow error converting varchar to data type numeric.
My first place where I could change is :
and change it to
ELSE try_convert(int, a.Marks)
or convert to decimal , if you want
In case expression you have a few THEN with different data types: int, numeric, varchar. Due to data type ...
Instead of processing DataGatheringRuntime table which is quite big at ~100GB) mutiples times
process it single time by putting them in #temp table or CTE
Then remove Distinct. If there is duplicate data then find the reason behind duplicate data
and remove duplicate data by writing correct query.
What is the purpose of Distinct and UNION in same query ?
WITH cte AS ( SELECT PolicyID,
COUNT(CASE WHEN Country = 'US' THEN 1 END) OVER (PARTITION BY PolicyID) us,
COUNT(Country) OVER (PARTITION BY PolicyID) total
If it were me?
Nuke it from orbit and restore from backup.
Stop any processes that rely on this database and restore from your most recent backups.
After you're stable, you can go through the academic exercise of trying to repair as much of the corrupt media as you've got the energy & budget to put up with. Assuming you have a strong understanding ...
For an arbitrary number of columns into a single row, you would have to build the dynamic SQL yourself. There may be cleaner ways than this, but the below is a start point.
Note that, unless the query optimiser can do something nice for you (which I doubt), it will scan the original data a huge number of times (at least 2 + colcount * rowcount):
In case an update can affect multiple rows, you have to protect against two things:
We want to consider updates that swap values between similar rows. If there are two John Smiths who need their JobCodes updated (first John from 1 to 2; second John from 2 to 1), we need to be careful to say they both were updated.
We only want to log the changed rows in ...
Avoid <> in where condition.Instead use >-1
When you are already filtering anything like where s.cfcifno<>-1 ,then no need of putting same in case condition because that condition is already filtered.
Your query seem ok to me,
SUM(CASE WHEN S.SATNAPAYATYPE=1 THEN S.AMOUNT ELSE 0 ...
You can try this.
@Stringss is a variable to simulate the field you already obtained
DECLARE @String NVARCHAR(MAX)='S:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\DATA\tempdb.mdf'
I've just been interested in this as well.
AFAICT using sys.dm_tran_current_transaction you can get the id of the current transaction.
Then with sys.dm_tran_active_transactions you can get all transactions with the transactions_begin_time
Hope this script includes all you are trying to retrieve.
This script retrieving CHECK and DEFAULT constraints. You can use INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE to retrieve PK & FK columns.
DECLARE @Constraint TABLE (
[Database] [nvarchar](128) NULL,
[Schema Name] [nvarchar](64) NULL,
[Table Name] [sysname] NOT NULL,
It's kind of a barebone question, but...
@DateToUse is the date you are searching for.
@StringOutput is the cto column.
I'm using the ID field as a tie-breaker in order to protect against duplicate or overlapping ranges in from/to fields.
DECLARE @DateToUse DATE
DECLARE @StringOutput VARCHAR(50)
SET @DateToUse = '3/2/2019'
SET @StringOutput = (...
what about doing one of these:
DENY SELECT ON SCHEMA::DBO TO PUBLIC (public or a login or set of logins)
ALTER ROLE [db_denydatareader] ADD MEMBER [your login]
Both worked for me and the complete test is below:
--create a login for testing
CREATE LOGIN Radhe WITH PASSWORD='HareKrishna001!', DEFAULT_DATABASE=master;
--create a database ...
Try using CASE expressions as you can specify qualifiers like what you're describing.
Select Count (*)
CASE when date >= 1st August year X THEN enteredondate = currentyear/08/01
ELSE enteredondate= previousyear/08/01
The Cursor approach:
DECLARE @statement NVARCHAR(100) -- statement
DECLARE @table SYSNAME -- Table name
DECLARE db_cursor CURSOR FOR
FROM sys.tables t
INNER JOIN sys.schemas s
ON s.schema_id = t.schema_id
WHERE s.name = 'dbo' -- or just test for schema_id = 1
FETCH NEXT FROM db_cursor INTO @table
WHILE @@FETCH_STATUS =...