text
stringlengths 209
10.7k
|
---|
<s>[INST]How to get zplid that have zfeature key value on all rows?
Exactly I need zplid and codetypeid that have feature value
on all rows .
if I have Null on zfeature key on one row then I don't Need it .
I need to get zplid that have features Not Null on all rows as zplid 9714
but 9823,5890 have Null so I don't Need it
this is my sample data
create table #gen
(
zplid int,
CodetypId int,
ZfeatureKey nvarchar(20)
)
insert into #gen(zplid,CodetypId,ZfeatureKey)
values
(9714,849774,1501290046),
(9714,849774,1501099991),
(9714,849774,1501555555),
(9823,9732410,1501290046),
(9823,9732410,1501099991),
(9823,9732410,NULL),
(5890,838651,1501290046),
(5890,838651,NULL),
(5890,838651,NULL)
expected result is
zplid CodetypId ZfeatureKey
9714 849774 1501290046
9714 849774 1501099991
9714 849774 1501555555
I tried to do as below :
select zplid,CodetypId,ZfeatureKey
from #gen
where ZfeatureKey is not null
but it give me zplid and codetypeid that have values ON Zfeature key on all rows of all zplid
and this I don't need
[/INST]I am not sure that this is the most efficient query, but it does the job:
; WITH CTE AS (
SELECT zplid, CodetypId, ZfeatureKey,
totalcnt = COUNT(*) OVER (PARTITION BY zplid, CodetypId),
nonnullcount = COUNT(ZfeatureKey) OVER(PARTITION BY zplid, CodetypId)
FROM #gen
)
SELECT zplid, CodetypId, ZfeatureKey
FROM CTE
WHERE totalcnt = nonnullcount</s>
|
<s>[INST]Using cast inside sum or outside ?
I work on sql server 2012 I face issue using cast first or sum ?
cast (sum(a) as decimal(18,2)
or
sum(cast (a as decimal(18,2)))
which is correct and more speed
a is integer need to convert to decimal
so using cast inside sum or outside[/INST]Just to be clear.
In your specific example, you can do an outer cast.
However, if you were going the other way, decimal to int, you would get different results depending on where you do that cast. Only you can determine which is correct.
DECLARE @testtbl TABLE (nums DECIMAL(18,2))
INSERT INTO @testtbl VALUES
(1.1),
(2.2),
(3.322),
(4.44)
SELECT CAST(SUM(nums) AS INT) -- = 11
SELECT SUM(CAST(nums AS INT)) -- = 10</s>
|
<s>[INST]SSMS does not have access to sys schema for master database - error is mssqlresourceserver schema sys execute permission denied
After trying to get a user to be able to execute a view - providing SCHEMA permissions, providing extended stored procedure permissions (directly) to the extended stored procedure specified to the error - no satisfaction. Oddly though, if the user does not right click the object so that it opens using the SSMS interface, but instead, writes the query ad hoc, there is no error.
Lately there has been some fairly tight restrictions come down the pipe about restricting extended stored procedure permissions and there is a notation from Microsoft the xp_ series will be deprecated in future versions.
I'm using the latest SSMS 18.7.1 and running on SQL Server 2019 Standard.
I have to wonder if this is a bug in the SSMS. Has anyone else run into this issue?
To recreate the issue, remove EXECUTE from xp_instance_regread
REVOKE EXECUTE ON [sys].[xp_instance_regread] TO [Public]
I even went so far as to create a role in each database (including master) and provided access to that extended stored procedure (to replace the permission removed from [Public] and added the users having the issue to those roles. Nothing seems to work (short of granting execute to public).
Has anyone encountered this strange situation? Did you find a work-around other than telling the user to run the query ad hoc rather than right clicking the object? (Select top 1000 xxx,yyy from Table)[/INST]I revoked permissions for public as you said. Then I connected to Object Explorer with an SQL login that owns a database, and in that database I tried to do SELECT TOP 1000 Rows, and indeed I got those errors.
Next, I did this in master:
CREATE ROLE regreaders
CREATE USER MyUser
ALTER ROLE regreaders ADD MEMBER MyUser
GRANT EXECUTE ON [sys].[xp_instance_regread] TO regreaders
Then I reconnected in Object Explorer (so that the tokens are picked up correctly.) I was now successful in running the SELECT TOP 1000 Rows.
However, I would suggest that if you have been told to revoke permissions on xps for public, you should start to grant permissions to users by other means, but tell people that they will need to use SELECT statements. Else you are not obeying to the guidelines that your security people have given. Also, personally, I don't like adding users to the master database.
As for editing posts, there is a cogwheel in the upper-right corner of your post. There is a menu which includes an Edit alternative (if the post is yours). For Comments, you find Edit under "More" below the post.</s>
|
<s>[INST]How to get parts that not have same features count on table settings by code typeid and pl ?
I work on sql server 2012 . if face issue I can't get parts that not have all features on table settings
so I will count distinct features from table settings and compare it with count features per part
if count features per part on table part feature \<\>count distinct features on table settings by PLID and code type
then display it .
as example part 9010 have only one feature 15000160 from table settings and not have feature 15000171
then display it .
as example part 9041 have only one feature 15000171 from table settings and not have feature 15000160
then display it .
part id 7731 have two features 15000171,15000160 as part settings have two features then no need
to display it because it have full features
so How to write query do that
create table #settings
(
SettingId int,
PLID INT,
CodeType int,
Code nvarchar(50),
featureKey int
)
insert into #settings
values
(1,2890,798541,'Ear99',NULL),
(1,2890,798541,'Ear70',15000160),
(1,2890,798541,'Ear99',15000171),
(1,2890,798541,'e900841',15000160)
create table #partFeature
(
PartId int,
FeatureKey int
)
insert into #partFeature
values
(9010,15000160),
(7070,15000171) ,
(9041,15000171) ,
(2030,15000160) ,
(5871,15000160) ,
(5871,15000171) ,
(7731,15000160) ,
(7731,15000171)
result I need
PartId FeatureKey
9010 15000160
7070 15000171
9041 15000171
2030 15000160
[/INST]Maybe also check this approach:
select *
from #partFeature
where PartId in
(
select PartId from
(
select f.PartId, s.featureKey
from #partFeature f, #settings s
where s.featureKey is not null
except
select *
from #partFeature
) d
)
However, it does not use the unclear *PLID* and *CodeType* columns.</s>
|
<s>[INST]How to Update status for pl data table when at lease one row part level = 1 for zplid ?
I work on sql server 2012 I have issue I need to update status for table pl data where i have at least partlevel=1
for every zplid ?
meaning I need to update status for historypl table by message 'have Correct Flag'
when it have only one row have partlevel=1 for zplid .
if zplid have only one row partlevel=1 on history pl table then update status to 'have Correct Flag' on table pl data
so how to do update statment ?
what i try :
update d set d.status='have Correct Flag' from #pldata d
create table #historypl
(
zplid int,
partlevel int
)
insert into #historypl(zplid,partlevel)
values
(2050,0),
(2050,0),
(2050,0),
(2090,0),
(2090,0),
(2090,1),
(2095,0),
(2095,1),
(2080,1)
create table #pldata
(
zplid int,
Status nvarchar(50)
)
insert into #pldata(zplid,Status)
values
(2050,NULL),
(2090,NULL),
(2095,NULL),
(2080,NULL)
expected result
zplid Status
2050 NULL
2090 have Correct Flag
2095 have Correct Flag
2080 have Correct Flag
[/INST]Check one of solutions:
update #pldata
set status = 'have Correct Flag'
where zplid in (select zplid from #historypl where partlevel = 1 group by zplid having count(*) = 1)</s>
|
<s>[INST]How to create table NEW_TABLE "like" OLD_TABLE including all column constraint definitions?
Hi All,
I am trying to create a copy of an existing table into a new table and retain all of it's old column definitions including all defined constraints. The table has over 200 columns, and typing in each constraint definition is tedious. I don't see a way in SQL Server to accomplish this without doing it one-by-one. What am I missing?
if (exists(select * from sysobjects where name = 'old_table' and type = 'U')) drop table old_table;
create table old_table
(
a char(1) not null default 'Y',
b integer not null default 0,
c datetime not null default '2020-01-01 00:00:00',
d integer null
);
insert into old_table (d) values (500), (null);
select * from old_table;
exec sp_columns old_table;
I want to create **new_table** from the definition of **old_table**. I want it to include all the constraints defined by **old_table**.
When I try and script the CREATE statement using SSMS, column constraints are not included. I could manually type each constraint definition, but I'm hoping there is an automated way of doing this.
Your help is appreciated!
Thank you.
--Dan
[/INST]Right click on your database, select Tasks and then Generate Scripts .... On the Choose Objects window, check "Select specific database objects" and then select the table you want to script. On the "Set Scripting Options" window, click on the Advanced button and then you can select any options you want, i.e., Script Indexes .... After the script is generated, replace the table name and constraint names (hope you have a good name convention on the objects). And then you can add the new columns in the script.</s>
|
<s>[INST]Disbaling Connection to a DB, allow only main admin account
Good day,
The dw db was opened for a few users to connect to at anytime with read access, but our dw dows not do paralism well and automation fails with out of memory or locked by another process (qlikview).
I wanted to do it differently where i populate a reporting db for users, however we have now users using qlikview running scripts on dw while main automations are running
is there a way or a step1 in a job i disable all users to connect to DW DB but for key accounts and then enable at last step for other users to connect or a schedule timer where dw db is only open for not it users to connect to dw automatically?
Please any ideas?
Thank you[/INST]Maybe this could be an option for you:
ALTER DATABASE yourdataase SET RESTRICTED_USER WITH ROLLBACK IMMEDIATE
Quoting Books Online:
> RESTRICTED_USER Allows for only members of the **db_owner** fixed database role and **dbcreator** and **sysadmin** fixed server roles to connect to the database. RESTRICTED_USER doesn't limit their number. Disconnect all connections to the database using the timeframe specified by the ALTER DATABASE statement's termination clause. After the database has transitioned to the RESTRICTED_USER state, connection attempts by unqualified users are refused.
At the end of the job, you would do
ALTER DATABASE yourdatabase SET MULTI_USER</s>
|
<s>[INST]Databases showed "recovery pending" (SQL 2019)
Hello,
- customer has one SQL 2019 Standard on a Windows 2016 Std. (vmware esxi) and he use four databases
- I restarted the Windows Server three different times in the last month because of application maintenance
- at two times SQL Databases showed in MS SQL Studio: **recovery pending**
adhoc Solution was:
- rightlick restarting SQL-Instance via Studio again
SQL Log I will post here later
Details:
abla_DB (very small)
import_DB (recovery pending) (import_DB.mdf = 3 GB, with approx. 60GB Filestream Folder), BAK = 65 GB)
practical_DB (recovery pending) practical_DB.mdf = 20 GB, with approx 1,5GB Filestream Folder, BAK = 20 GB)
system_DB (very small)
Side-Infos:
- Veeam Backup and Replication is doing Image-Backup
- no SQL Dumb backup via sql agent configured yet
- before reboot I manually stopped onetimes SQL Server Instance Service, looks like no effect
- the Server is installed since 1-2 month
Can you help me find the cause?
Thx + Best Regards in advance!
[/INST]I see this:
> 12/31/2020 10:38:54,Server,Unbekannt,SQL Server detected 12 sockets with 1 cores per socket and 1 logical processors per socket<c/> 12 total logical processors; using 4 logical processors based on SQL Server licensing. This is an informational message; no user action is required.
And this:
> 12/31/2020 10:27:08,spid11s,Unbekannt,A failure occurred while FILESTREAM configuration was being changed or applied. For more information<c/> see the SQL Server error log.
> 12/31/2020 10:27:08,spid11s,Unbekannt,FILESTREAM: effective level = 0<c/> configured level = 2.
> 12/31/2020 10:27:08,spid11s,Unbekannt,FILESTREAM: failed to connect to kernel driver RsFx0600.<nl/><{1038F43D-3391-45F7-B1B3-BADF26459429}>Failed to initialize CFsaShareFilter: Error 0x80070015 (-2147024875)
You could try setting the SQL Server service to delay start - as it seems some of the drives may not be available after a server restart.</s>
|
<s>[INST]sql 2019 server cals
Hello
where do we install the sql server 2019 cals ? how do i know if my cals are all used ?
thank you[/INST]CALs are just pieces of paper. They are not installed or tracked anywhere in the system.</s>
|
<s>[INST]Max size of data to be encrypted
Max size of data decrypted by CONVERT(varchar, DecryptByKey(encripted_data)) is only 30?[/INST]Yes. Since you don't specify any length, you get a default of 30. With CONVERT, I should hasten to add. If you say
DECLARE VAR varchar
you get varchar(1).
So always specify the length explicitly!</s>
|
<s>[INST]SQL Server DB Backup - Backup Compression and Timing
Hi All,
We are using PeopleSoft Application (HRMS and FSCM) and it's running on SQL Server 2014 Enterprise Edition.
Here the FSCM DB Size is 440GB and HRMS DB Size is 395 GB.
We are taking daily DB Backup's for both HRMS and FSCM Database and using the "Compress Backup" under the Backup Settings.
Here is my question..
When i compare both the DB's FSCM Database is much larger when compared with HRMS Database (i.e around 45 GB additional on FSCM Db).
1. When taking backup, FSCM Backup job gets completed around 40 minutes and HRMS Backup Jobs takes nearly 1 hour and 45 Minutes to complete.
Please note that during the Backup Job timings, we dont have any workload on the Database (i.e.. all the PeopleSoft Job's and DB's Jobs are disabled during this backup timing). My question is why the HRMS db backup job is taking much longer time when compared with the FSCM backup job (i.e triple the time it takes). Also if you could note the HRMS Database is smaller when compared to FSCM database and HRMS DB Backup job is taking triple the time when compared to FSCM Backup Job timing.
Please suggest.
2. If i refer the Backup file, FSCM Db backup file size is 138 GB and the HRMS DB backup file size is 254 GB. Here we have set to COMPRESS BACKUP for both the Database, but not sure why the HRMS DB backup file is larger when compared to FSCM db backup file size.
If you could notice the Physical db size, HRMS Physical DB is smaller when compared to FSCM Physical db but the backup file is larger here..
Please suggest.
regards
Dhana
[/INST]My question is why the HRMS db backup job is taking much longer time when compared with the FSCM backup job (i.e triple the time it takes)
Without any concrete performance data it's hard to say but I'll make an educated guess that it's due to the size of the final backup (in this case 254GB which is almost twice the backup size of the other database at 138 GB), so writing double the data to the disk is most likely taking up a good portion of the extra time... but again no performance data from the disks, cpu, memory to show this.
>Here we have set to COMPRESS BACKUP for both the Database, but not sure why the HRMS DB backup file is larger when compared to FSCM db backup file size.
Compression results vary based on the type of data and the amount of entropy in the data, among other things. This is just telling you that the data in one database is apparently better for compression than another, so it has a better compression ratio. A quick example is that certain types of text usually compresses very well, but numeric digits may not as there may not be much uniformity to their layout. It also depends on the algorithm type, dictionary size, etc., which in this case you can't control.
There isn't really a whole lot you can do except figure out which item is the bottleneck in the setup (disk/memory/cpu/etc) and tune/get faster/better/etc. as 138GB in 40 mins = 58MB/sec and 254GB in 105 mins = 41 MB/sec which is very slow by most modern standards.</s>
|
<s>[INST]Multiple tables or 1 big table
Hi,
I'm going to log the consumption (water, electricity, gas, ect) for plenty of devices (take 400 devices which log every hour and we need to keep the data at least 2 or 3 years) .
Now i was wondering if i can better put them in 1 table with the following colums:
[Type][Device][Value][Date]
Type: Water, Electricity or Gas
Device: Which device we are logging
Value: The actual value
Date: date when the record was logged
Or can i better create a table for every device with only 2 column (Value and Date).
Because when i need the data for reporting, i never going to need all the devices (report we want to make are 32 devices).
I can make the Type and Device column indexed, but performance wise isn't it better to read only the tables i need?
Or is it more difficult to read multiple tables at the same time?
Thanks at advance!
Kind regards,
Ward [/INST]400 devices x 24 h x 365 days x 3 years = 10.5 million records, that is **very less** data; go the way with one table.
I have tables with billions of records and no performance issues.
One table per device has the disadvantage, that you always have to add a new table if you get a new device, you have to change reports, and so on.</s>
|
<s>[INST]What are JFM, MDL files in Visual Studio Database Project?
I am trying to create a Visual Studio Database project to ensure my databases are scripted and version controlled. Post creating the project file I see the following files being created in the folder
.sln (Solution File) (Need to checkin, IMHO)
.sqlproj (.SQL Project File) (Need to checkin, IMHO)
.sqlproj.user (My guess is that it can be added to .gitignore)
.jfm (Could not understand the significance of this file)
.mdl (Could not understand the significance of this file)
[/INST]MDL should be temporary files. I usually stage only required files like .sln, .sqlproject and checking the staged changes</s>
|
<s>[INST]SQL Server 17default User Groups Not Created for Windows 10: cannot assign permissions to folders
I've just installed SQL Server 17 on Whindows 10 (with latest updates) and wish to grant permissions for SQL Server to open up mda files from a second drive. When attempting to grant permissions to the drive, I do not see any of the NT Services (e.g., MSSSQLSERVER) to grant permission to. In the Computer Management/Users form, they also no not show up under the UserGroups.
Was this an install error or is there another method for SQL 2017 to be granted permissions to Windows 10 folders?[/INST]What is the service account according to sys.dm_server_services?
The service SIDs, for instance NT Service\MSSQLSERVER, does not show up User and Groups on my machine, so that seems normal that you don't see them.
I usually type NT Service\MSSQLSERVER and then press Check Names when I want to grant permissions to an SQL Server instance.</s>
|
<s>[INST]Performance and Linked servers
Hi All.
I have a setup whereby I need to retrieve data from a different database, what I found is that if I run the query directly from the source database and use PowerShell to copy the data onto my test database, the query runs within seconds. If I however setup a linked server from my test database (SQL 2014) instance to the source database (SQL 2014) , and run the same query using linked servers, it runs for over 40 minutes without completing.
It has made me think, apart from PowerShell for transferring data from source database onto my test database, what other options are available which doesn't suffer performance limitations.
Lastly, when using linked servers on SQL 2014, are there any factors that affect linked server query performance ?
Thanks in advance.
[/INST]Linked servers often mean hassle. And that includes performance issues. Say that you have a query that goes like:
SELECT ...
FROM SERVER.db.dbo.tbl A
JOIN SERVER.dbo.dbo.othertbl B ON ...
WHERE ...
What you want to happen is that this query is executed on the remote server and the local server just gets the data. And sometimes. this is also what happens. But sometimes it does not, but instead,the local SQL Server drags the full tables over to the local server to perform the join and filtering on that side.
There is more than one reason why this can happen, and I am not going to detail all, but only mention one reason: the query includes a construct which cannot be "remoted", that is be executed on the remote side. Keep in mind that, linked servers is a generalised feature. SQL Server queries a remote source, which could be anything - SQL Server, Oracle, Postgres or your own homebew - and asks the OLE DB provider about the capabilities of the remote source. But if there is no good question to ask, SQL Server simply will have accept that remoting is not possible.
For a query like the one above, there is a simple workaround: slap the whole thing in OPENQUERY, which tells SQL Server to run the query on the remote server without further questions. But if you need to join local and remote tables, it gets more challenging.
Using a Powershell script as you did is absolutely a good option and it avoids many of the issues with linked servers. (Which is not only performance, but there can also be Kerberos problems or problem with DTC.) Other options is to use an SSIS package or to use BCP or just a different programming language.</s>
|
<s>[INST]SQL linked server
Hi All,
I need to rename table name from cross server.I have linked server(Azure SQL server is the destination where I need to rename) in server object but I cannot rename using it.Could you please help me with the script for it.
Thanks,
Brindha[/INST]What do the linked server has to do with it?
The normal thing to do would be to connect to the instance where the database resides, and run
EXEC sp_rename 'MyTable', 'MyRenamedTable'
If you want to do it across a linked server, you can do:
EXEC SERVER.db.sys.sp_rename 'MyTable', 'MyRenamedTable'</s>
|
<s>[INST]SQL Server query loggin
When i execute a drop view query i don't see it in the query logging.
Goal is to store all the executed queries. How can i achieve this?
use [MY_DB]
go
create view test as select '1' as one
; go
DROP VIEW [dbo].[test] ;
SELECT sql_text.text, st.last_execution_time, DB_NAME(qp.dbid) as databasename FROM sys.dm_exec_query_stats st CROSS APPLY sys.dm_exec_sql_text(st.sql_handle) AS sql_text INNER JOIN sys.dm_exec_cached_plans cp ON cp.plan_handle = st.plan_handle CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle) as qp WHERE st.last_execution_time >= DATEADD(week, -1, getdate()) ORDER BY last_execution_time DESC;
[/INST]Goal is to store all the executed queries. How can i achieve this?
You'll need to create your own auditing via any of the many tools that exist for this: Trace (deprecated), XE, Audits (also XE under the covers). In your example, there is DDL and since there is only a single way to execute DDL it doesn't make sense to have and cache a plan for it.</s>
|
<s>[INST]Not able to see data from ## table if changing server
Hello - I have added data in ##1 and #2 using server/database-ACL-SQLSER1.CHG_N1 but when I moved the server and running the query in another server/database-ACL-SQLSER2.CHG_N2 then I am unable to see the data of ##1 and #2 and gets the following error. I don't want to use the Linked server due to access. Is there a way to see the data in ACL-SQLSER2.CHG_N2 after changing the SQL-server.
ACL-SQLSER1.CHG_N1
Select * into ##1 from temp OR
Select * into #2 from temp1
ACL-SQLSER2.CHG_N2
Select * from ##1 OR
Select * from #2
Error:
Invalid object name '##1'
Invalid object name '#2'[/INST]I'm not sure I understand this correctly, but it seems that you are in London, go down to the river and leave a things down there. Then you fly over to Paris, and you do down to the river and expect to find the things you left in London?
The temp tables you defined exists only on the server where you created them. And the one called #1 is only visible to the process that created them. The one called ##2 is visible to all processes on that server - but only as long as the process that created them is still around.
If you are on server A and want to access server B, you need to use one of:
- Linked server.
- OPENROWSET/OPENDATASOURCE
- xp_cmdshell + SQLCMD.
- CLR procedure that connects to the instance.
- A Python or R scripts that connects to the other machine.
I there are permission issues with the linked server, I should warn you that about all the other will require more permissions.</s>
|
<s>[INST]How to run pssdiag on a single database?
Hi, I would like to run pssdiag on a single database using Diagmanager (instead of the whole instance), is it possible to do that?
Pretty much i would like to filter the profiler trace to be run only on 1 database... Just like if you just run sql profiler - you can filter and mention the database... I don't see a way to goto the 'Profiler Trace' tab of diagmanager and 'choose' a database...
Thanks.[/INST]It seems we cannot filter the database in pssdiag.
This tool seems to only collect data for the entire instance.</s>
|
<s>[INST]SQL Best Practices
Hi All,
Need some advice on the below questions please
* Is there any best practices to manage shared DB.
* Just wanted to understand, how patching is managed for shared DB without any downtime. Is there any load balancer used normally
[/INST]Is there any best practices to manage shared DB.
Every database is "shared" = used by multiple application & user, that's the nature of databases/SQL Server. I don't understand what you want to manage here?
> Just wanted to understand, how patching is managed for shared DB without any downtime. I
As other updates/patches it require a downtime to install it. High availability solution like clustering/AlwaysOn helps to keep the downtime short.
> Is there any load balancer used normally
The is not really "load balancer" concept in database world. In AlwaysOn or replication solution you can have e.g. a read-only replica of the database(s).</s>
|
<s>[INST]Unable to apply security updates
Hi there,
Following a recent security scan of our SQL servers, it was noted that KB4458621 and KB4293802 were missing.
I downloaded these and attempted to apply them but was unable to do so. When I ran the update, the dialog box that shows the instances that are available for patching showed the instance, but would not let me select it. Normally, if there is only one instance on a server, this check box is selected by default. There is only one instance on this server.
The current version is SQL Server 2016(SP2-CU15)(KB4577775) Version 13.0.5850.14
This issue occurred trying to apply both patches.
Please advise
Thanks
[/INST]As TomPhilips mentioned, each new CU contains all the fixes that were included together with the previous CU for the installed version of SQL Server. So you do not need to and you cannot install previous CU (KB4458621 and KB4293802) on new CU for SQL Server (KB4577775).
And this is the reason that the instance you want to patch does not let you select it.</s>
|
<s>[INST]Compare two table columns,
Compare two table column ,if Item_Rate of B_ID against Level_Four_ID exit in #tbl_Assign ,then item_Rate Pick from #tbl_Assign,if Item_Rate does not exit in #tbl_Assign of B_ID, then rate will pick from #tbl_bottles .
I Created below condition ,in which i defined B_ID=2,which is not exit in #tbl_Assign ,but exit in #tbl_bottles,then rate will pick from #tbl_bottles.but my query is not taking ouput
Create table #tbl_bottles(B_ID int,B_Name varchar(50),Rate int)
Create table #tbl_Account_L_Four (Level_Four_ID int,Level_Four_Name varchar(50),Opening decimal(10,2),Opening_Date date)
Create table #tbl_Assign (Assign_ID int,Level_Four_ID int,B_ID int,item_Rate int)
INSERT INTO #tbl_Account_L_Four VALUES(1231,'Abdul Rauf',60000,null)
INSERT INTO #tbl_Account_L_Four VALUES(1222,'Cheque In Hand',45000,'2021-01-17')
INSERT INTO #tbl_Account_L_Four VALUES(1215,'MBL 833968',0,null)
insert into #tbl_bottles VALUES(1,'A',50)
insert into #tbl_bottles VALUES(2,'B',60)
insert into #tbl_bottles VALUES(3,'C',70)
insert into #tbl_Assign VALUES(11,1231,1,150)
insert into #tbl_Assign VALUES(12,1231,3,350)
select Isnull(A.Item_Rate,B.rate) as rate From #tbl_bottles B left join #tbl_Assign A on A.B_ID=B.B_ID
where B.B_ID = 2 and A.Level_Four_ID=1231
[/INST]Please try the following.
SELECT CASE WHEN ass.item_Rate IS NOT NULL THEN ass.item_Rate ELSE btl.Rate END AS rate
FROM #tbl_Account_L_Four AS acc
CROSS JOIN #tbl_bottles AS btl
LEFT JOIN #tbl_Assign AS ass ON(ass.Level_Four_ID = acc.Level_Four_ID AND ass.B_ID = btl.B_ID)
WHERE acc.Level_Four_ID = 1231 AND btl.B_ID = 2</s>
|
<s>[INST]Stop user access when updating Tables?
Hi,
We are going to run some scripts from consultant to update some tables in a SQL Server Database.
We would like to block end users from accessing that database during our update. Is it feasible ? If not, can we disconnect all users from the database before we perform the update ?
Thanks[/INST]You can do one of
ALTER DATABASE TheDb SET SINGLE_USER WITH ROLLBACK IMMEDIATE
ALTER DATABASE TheDb SET RESTRICTED_USER WITH ROLLBACK IMMEDIATE
SINGLE_USER means just one. You can have one single query window open to the database, and you will not have Intellisense available, since it uses a second connection. Also, any services etc will also be thrown out.
RESTRICTED_USER means that only users who are in the db_owner or sysadmiin roles can access the database. This is less restrictive and permits multiple members of the DBA team to connect. Note that if the application against best practice connects as dbo or sa, this option is not going to lock out users.
Once you are done, you open the database with
ALTER DATABASE TheDb SET MULTI_USER</s>
|
<s>[INST]Can OS pressurize SQL to release memory?
In which of the following two cases, OS can pressurize SQL to release memory.
Suppose a VM has 6Gb RAM
1. If I set sql MAXMemory to 3Gb (without setting Lock pages in memory), would OS be able to free some memory from sql if it needs.
2. If I set sql MAXMemory to 3Gb (And also set Lock pages in memory), would OS be able to free some memory from sql if it needs.
Can OS really pressurize SQL to release memory? I have not encountered any such issue when using non-default value in MAXmemory setting.
Thank you in advance
[/INST]So Windows does not just go and grab the memory from SQL Server and give it to someone else - that could have been drab effects.
But SQL Server listens to the OS, and if SQL Server finds that there is memory pressure in the machine, it will yield, mainly by giving up data in its caches. And this is true, no matter you have "lock pages in memory" set.
You can easily try this by first getting a lot of data into the buffer cache so that SQL Server maxes out is 3GB of RAM. Then you can start something else that needs memory, and if you monitor sys.dm_os_process_memory, you will find that SQL Server memory will decrease.
If you have not seen this, it could be that you have not been able to find a process that grabs that much memory. Tip: another SQL Server instance could be a thing to try.</s>
|
<s>[INST]Is it a good practice to limit the tempdb data files size when the drive is getting full
I am seeing an issue wherein the tempdb drive is given only 50 GB size(4 tempdb data files are present within the drive) and the drive is getting filled up during maintenance job run due to increase in tempdb file sizes. I was told by the server team that they cannot increase the drive size and instead asked me create additional files in some other drive which has enough free space.
I have created additional 4 files in a separate drive, but the old drive is still getting full. Can I limit the max file of the datafiles to avoid disk space issues? Please advise if there would be any performance issues for doing so.
I have already asked the client if I can move all of the files to the new drive, but client is not okay with that, so that option is ruled out.
Thanks in Advance![/INST]When you specify the files, ensure they ALL have the same initial size and growth size. You want to ensure a proportional fill of the files.
Work out the total size you need for the processing (for example let's say 80 GB). From that also work out the space you have available on the original drive (for this example, let's say 20GB). Now the 20GB you had available is for 4 files - so each is allowed up to 5GB. Therefore to keep your balanced fill you need to create 60GB worth of files with each file allowed up to 5GB -> you need 12 files and not just the 4.</s>
|
<s>[INST]Conversion failed when converting the varchar value 'BB-2' to data type int.
I am inserting BB-1 ,then again ,BB-2 is generating , it is giving error.
Conversion failed when converting the varchar value 'BB-2' to data type int.
CREATE TABLE #tbl_Sell_M(Bill_No varchar(10),E_Date date)
WITH cte AS (SELECT 1 AS Bill_No
UNION ALL
SELECT TOP (1) Bill_No + 1 AS Bill_No
FROM dbo.tbl_Sell_M AS t
ORDER BY Bill_No DESC)
SELECT TOP (1) CONCAT('BB-', Bill_No) AS Bill_No
FROM cte
ORDER BY Bill_No DESC
[/INST]If *tbl_Sell_M* is empty then it works. But if it contains something like ‘BB-1’ or ‘BB-2’, then it is not possible to calculate *Bill_No + 1*.
Consider using integers (*int* column) without ‘BB-‘ (which can be prepended later), or try this workaround, which is probably less recommended:
WITH cte AS (SELECT 1 AS Bill_No
UNION ALL
SELECT TOP (1) stuff(Bill_No, 1, 3, '') + 1 AS Bill_No
FROM tbl_Sell_M AS t
ORDER BY Bill_No DESC)
SELECT TOP (1) CONCAT('BB-', Bill_No) AS Bill_No
FROM cte
ORDER BY Bill_No DESC</s>
|
<s>[INST]sql studio management studio "how do i" feature missing
Hello,
I've installed SQL server management studio 18.9.1
Out of the box, it's completely missing the dynamic help and the "How do I" entry in the help menu.
Is there something I'm missing? How could I enable it?[/INST]In the latest version of SSMS - you can configure help to launch in a browser or locally. To configure for local use - you need to download and install the necessary help files. You can use Help | Add and Remove Help Content to download the help files you want to store locally.
If you don't download any content - the default will open the help in a browser.</s>
|
<s>[INST]SQL Server Express 2019 Architecture
Is SQL Server 2019 Express edition available in 32-bit or is it 64-bit only?[/INST]SQL Server 2014 was the last version to have a 32-bit version of SQL Server.</s>
|
<s>[INST]Table composite Index position has performance affect?
Hello, we have the following similar Index on a particular table as example:
CREATE NONCLUSTERED INDEX \[Products_IDX\] ON \[dbo\].\[Products\]
(
\[Product_ID\] ASC,
\[Purchase_Date\] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON \[PRIMARY\]
GO
When running like a Delete statement (on a large table) using a WHERE clause on \[Purchase_Date\] column will the Delete statement run faster or since the position of this column is not the first one listed it will not be used and performance will be slow?
Thanks in advance.
[/INST]The delete statement will not be able to seek the index to find the rows, since the purchase_date isn't the first column in the index key. It might scan the index, you'd have to consult the execution plan to see what it decided.
You can execute that create index command, but it will be blocked by the delete operation since it requires a very restrictive locked - and the delete also has conflicting locks. When the delete has finished and released it locks, the create index can proceed.</s>
|
<s>[INST]Format Decimal column
Hi.
I am trying to format a column, so that value is displayed in 30 characters before the decimal and 4 places after the decimal.
Example: +000000000000000000000002500000.0000 ( + or - depending on the value ) .
I tried the below:
select CAST(ISNULL(NULLIF(columnName, ''),0) AS DECIMAL(30,4)) from table.
But this does result in the patter required. How to format this , as shown in the example?
Thanks[/INST]Try this:
select format( cast(isnull(nullif(columnname, ''),0) as decimal(34,4)), '+000000000000000000000000000000.0000;-000000000000000000000000000000.0000')</s>
|
<s>[INST]Add between date and a specific date
Hi,
In one of our feed I need to add between date and also a specific date
WHERE
sof.Sales_Office = @SalesOffice
and
s.postage = 'Y'
and
s.[Order Date] >= @FromDate and s.[Order Date] <= @ToDate
How would I say the above **and** s.[Order Date] = '02/06/2017'
Thanks for help.
[/INST]If you want to get data for a specific date addtional to the date range, then it's a OR logic, not AND; don't forget the brackets =>
WHERE sof.Sales_Office = @SalesOffice
ands.postage = 'Y'
and (s.[Order Date] >= @FromDate and s.[Order Date] <= @ToDate
OR s.[Order Date] = '02/06/2017')</s>
|
<s>[INST]Not able to cast nvchar as number
Hi,
We have had some SQL thats been running for about a year and it has suddenly stopped working.
CAST(ISNULL(M.DEFINED_KEY1, 0) AS NUMERIC(9, 0)) AS [No_of_Cats]
It basically puts a 0 instead of null and then makes it numeric.
I have checked the column and all it has in it is nulls or integers.
Anyone got any idea why this would suddenly stop working?
The error im getting is
> Error converting data type nvarchar to numeric.
The largest number in the field is 1100000, the smallest is 0 and Null is the only other type of value.
[/INST]"I have checked the column and all it has in it is nulls or integers."
You might have checked the data visually, in that case you have garbage in the data which doesn't show up visually.
The trick is to find those rows, and those rows only. Below show you how you can do that. In your WHERE clause, use IS NOT NULL so you don't return the rows which are NULL and also use TRY_CAST to find those that aren't convertible to int:
DROP TABLE IF EXISTS #t
CREATE TABLE #t(c1 int identity, c2 nvarchar(10))
INSERT INTO #t(c2) VALUES ('1')
INSERT INTO #t(c2) VALUES ('123')
INSERT INTO #t(c2) VALUES (NULL)
INSERT INTO #t(c2) VALUES ('12' + CHAR(9)) --Note that CHAR(9) is TAB
--It looks like data is fine!
SELECT * FROM #t
--But conversion fails because of TAB
SELECT c1, CAST(c2 AS int)
FROM #t
--How to find the failed rows, and those only?
SELECT c1, c2
FROM #t
WHERE c2 IS NOT NULL
AND TRY_CAST(c2 AS int) IS NULL</s>
|
<s>[INST]Operand data type varchar is invalid for sum operator.
i am doing sum of Trans_Amount ,but error is coming.
;with cte as (
SELECT T.Trans_ID as ID,COnvert(varchar,T.Trans_Date,101) as Date,COA.Level_Four_Name as Head,T.Cheque_No ,
Convert(varchar,T.Cheque_Date,101) as Cheque_Date,T.Cheque_Bank,T.Cheque_Branch
,(CONVERT(varchar(50), CAST(t.Trans_Amount AS money),1)) as Amount,T.Cheque_Status
FROM tbl_transection T
inner join tbl_COA COA on COA.Level_Four_ID=T.Level_Four_ID_C
where T.Trans_Type_ID=2 )
select 'Total' ,SUM((CONVERT(varchar(50), CAST(cte.Amount AS money),1))) from cte
[/INST]The error message is pretty clear isn't it? Your CTE returns a string and then you are trying to perform an arithmetic operation on a string. I mean what is the sum of New York, London Paris and Munich?
I think you should ask yourself why you put in that convert in the CTE in the first place.</s>
|
<s>[INST]A database with datafile size 418 GB backup is running very slow
A database with simple recovery mode and datafile size 418 GB, backup is really slow. What is the fastest way to backup the database.[/INST]The fastest way is a snapshot-based backup. Which is nothing you do from SQL Server, but typically something you do on your SAN. And just because the backup is faster, it does not mean that the restore will be smooth.
What environment is this? If the backup is slow, this is because your storage subsystem is what it is.</s>
|
<s>[INST]Query store
Experts,
Query store is used for capturing a history of executed queries,, execution plans etc. against a specific database. However just to understand what is the impact of enabling it in read-write mode on the general performance. Does it utilize a lot of resources and might impact the overall performance in the long run. For SQL 2017/2019 versions.
[/INST]it is said that Query Store adds an overhead of 3-4%, and this is perfectly tolerable. Not the least when you take in consideration that it can help you to improve performance by finding slow queries.
However, there are workloads where Query Store can take SQL Server over the brink. The typical case would be an application that submits a lot of short quick queries, and it is even worse if they are unparameterised. They have improved this in SQL 2019 by providing different capture more, and the default mode, AUTO, will ignore these single-use queries.
Query Store is a tremendous asset, and I think you should turn it on, and only turn if off, if you find that it causes problems.</s>
|
<s>[INST]nth Occurence Join
I am very stuck with this. I have two tables:
**Table 1:** Patients and CPT values that all say SURG
PATNOCPT58903SURG58903SURG**Table 2:** Has same patients but with actual codes I need to match with Table 1.
PATNOCPT5890329882589036447
**The issue:** Vlookup only gets first lookup value and I need to populate all the occurrences, not just the first. For Patient 58903, I would like my vlookup to populate the first instance with 29882 and the second with 6447 if possible. I was thinking I could do this easier with SQL? Maybe a left join with a condition but I'm not quite sure how. Any help would be very, very appreciated.
[/INST]Maybe you need a query like this:
;
with Q1 as
(
select *, row_number() over (partition by PATNO order by ID) n
from Table1
),
Q2 as
(
select *, row_number() over (partition by PATNO order by ID) n
from Table2
)
select isnull(Q1.PATNO, Q2.PATNO) as PATNO, Q1.CPT as CPT1, Q2.CPT as CPT2
from Q1
full outer join Q2 on Q2.PATNO = Q1.PATNO and Q2.n = Q1.n
order by Q1.PATNO, Q2.PATNO, Q1.n, Q2.n
where *ID* is the primary key of tables. (Use the real column name instead of *ID*, or give details, or use other columns that allow precise ordering).</s>
|
<s>[INST]Enable read-only replica alwaysON & HA platform
Hi
I'm setting up high availability for my SQL 2017 STD platform.
I currently have a WSCF with 2 nodes and the data on NAS. It works perfectly.
Now I have configured the AlwaysON on an additional server and the secondary replica has been successfully established.
1.- Do you think this platform is correctly configured for HA? or do you advise it to be all AlwaysON?
2.- How can I access the AlwaysON replica so that the reports and other apps can access it? I can't change the "Readable Secondary" value to YES[/INST]The purpose of Availability Groups in Standard Edition is to support a single database in either HA or DR. Since it does not support multiple databases or read-only it cannot be utilized for those purposes.
Your configuration was already HA using a failover instance - such that one node fails and the other node takes over. The only benefit to a BAG in that scenario is possibly less time during that failover event. This is because the secondary instance is already running and you skip a lot of the startup processes.
If you need read-only, then you have to upgrade the primary and secondary instances to Enterprise Edition.</s>
|
<s>[INST]Insert data in Parent and child table
I know update and delete cascade will update and delete automatically in child table when any changes happen in parent table but how about insert data in parent , does insert data in parent table will automatically insert in child table [/INST]Here is a script to illustrate what Viorel said. I can't say that I find the request particular meaningful - in most cases you don't know the child data only from the parent.
CREATE TABLE parent (ParentId int NOT NULL,
ParentName varchar(20) NOT NULL,
CONSTRAINT pk_parent PRIMARY KEY (ParentId)
)
go
CREATE TABLE child (ParentId int NOT NULL,
ChildNo int NOT NULL,
ChildName varchar(20) NOT NULL,
CONSTRAINT pk_child PRIMARY KEY (ParentId, ChildNo),
CONSTRAINT fk_child_parent FOREIGN KEY (ParentId) REFERENCES parent (ParentId)
)
go
CREATE TRIGGER parent_tri ON parent AFTER INSERT AS
INSERT child (ParentId, ChildNo, ChildName)
SELECT ParentId, 1, ParentName
FROM inserted
go
INSERT parent(ParentId, ParentName)
VALUES(11, 'Jim')
go
SELECT * FROM parent
SELECT * FROM child
go
DROP TABLE child, parent</s>
|
<s>[INST]COUNT occurence of X,Y across columns
Hi all,
SQL noob here :) I currently have data presented in such a format where col 1 = number of trips 2 = origin postcode 3 = destination (UK) post code,
1 2 3
1 PR5 0XD AB23 8HG
1 PR5 0XD B24 8TG
1 PR5 0XD B24 8TG
1 PR5 0XD B24 8TG
1 PR5 0XD B24 9QJ
1 PR5 0XD B6 7AX
1 PR5 0XD BA4 4PW
1 PR5 0XD BA4 4PW
1 PR5 0XD BB1 2PT
1 PR5 0XD BB1 2PT
1 PR5 0XD BB1 2PT
1 PR5 0XD BB1 2PT
1 PR5 0XD BB1 2PT
1 PR5 0XD BB1 2PT
1 PR5 0XD BB1 2PT
1 PR5 0XD BB1 2PT
1 PR5 0XD BB1 2PT
I need to write a query so the information is grouping the occurences of the trip as so;
for example below, where 9,4 are no. of occurences in the dataset of the pair.
9 PR5 0XD BB1 2PT
4 PR5 0XD B24 8TG
and so on...
I tried this script but it output the top results set, with no grouping,
SELECT count (load_id) as number trips, origin_zip,Destination_Zip
FROM [Rep_UK].[dbo].[Main_table_UK]
WHERE Origin_Zip = ('pr5 0xd')
GROUP BY Load_ID,Load_Carrier_ID,origin_zip,Destination_Zip
HAVING COUNT(*) >= 1;
any help much appreciated!!!
thanks
Jamie
[/INST]Did you also try the next query?
SELECT count (load_id) as [number trips], origin_zip, Destination_Zip
FROM [Rep_UK].[dbo].[Main_table_UK]
WHERE Origin_Zip = 'pr5 0xd'
GROUP BY origin_zip, Destination_Zip</s>
|
<s>[INST]How to skip space in a query
Hello,
I am trying to alter credentials using a SQL query "ALTER CREDENTIAL credential_name WITH IDENTITY = 'identity_name'
[ , SECRET = 'secret' ]"
And the issue is that my credential_name has a space in it. so that would make my query look something like:
ALTER CREDENTIAL HCC SQL WITH IDENTITY = 'username', SECRET = 'password';
Which gives me the following error:
Msg 102, Level 15, State 1, Line 4
Incorrect syntax near 'SQL'.
Msg 319, Level 15, State 1, Line 4
Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.
So I was wondering if there is a way to skip the space in this query?
Or would I have to change my credential_name to something with no spaces?
Thanks[/INST]ALTER CREDENTIAL [HCC SQL] WITH</s>
|
<s>[INST]Ad Hoc Distributed Queries
Hi,
We are using SQL Server 2017 in our production environment. We got following requirement from our security team.
*Ensure 'Ad Hoc Distributed Queries' Server Configuration Option is set to '0'*
Is there any impact for database connection if we disbale this'? Our application use linked servers frequently. Does it related to linked server?[/INST]If you use linked servers in the true sense, there is no issue. That is, you have created linked servers with sp_addlinkedserver and refer to them with four-part notation or OPENQUERY there is no issue for you.
On the other hand, if you use OPENROWSET or OPENDATASOURCE, your security team wants you to rework your code. There are sort of linked servers set up on the fly for the query.</s>
|
<s>[INST]merging data from another table in another database SQL
Dear all
I currently have this query
SELECT count (load_id) as [number trips], origin_zip, Destination_Zip,Load_Carrier_ID,Load_Carrier_Description
FROM [Rep_UK].[dbo].[Main_table_UK]
WHERE Origin_Zip = 'pr5 0xd'
AND [Trip Type] = 'roundtrip'
AND Empties = 'false'
AND datepart(year, convert(DATETIME2, deliveryDate, 103)) = 2020
GROUP BY origin_zip, Destination_Zip,Load_Carrier_Description,Load_Carrier_ID
HAVING COUNT(*) >= 1;
and I need to incorporate into this the below so it also filters from another (TMS) database,
select* from
[dbo].[DB_TMS]
where Load_Service_ID like '%LTL%'
if anyone can let me know how I should incorporate into one query would be greatly appreciated!!
thank you
[/INST]It is recommended to provide DDL and sample data of both tables , relationship with each other and expected output.
If you would like to combine the results of both queries and they have similar columns, you could use UNION/UNION ALL as below:
SELECT count (load_id) as [number trips], origin_zip, Destination_Zip,Load_Carrier_ID,Load_Carrier_Description
FROM [Rep_UK].[dbo].[Main_table_UK]
WHERE Origin_Zip = 'pr5 0xd'
AND [Trip Type] = 'roundtrip' AND Empties = 'false'
AND datepart(year, convert(DATETIME2, deliveryDate, 103)) = 2020
GROUP BY origin_zip, Destination_Zip,Load_Carrier_Description,Load_Carrier_ID
HAVING COUNT(*) >= 1
union
select 0 [number trips], origin_zip, Destination_Zip,Load_Carrier_ID,Load_Carrier_Description
from [dbo].[DB_TMS]
where Load_Service_ID like '%LTL%'
If you would like to add one condition into the first query, you could use exists/in once they have one unique column.
Please also refer below method which uses IN:
SELECT count (m.[load_id]) as [number trips], m.[Origin_Zip], m.[Destination_Zip], m.[Load_Carrier_ID], m.[Load_Carrier_Description]
FROM [Rep_UK].[dbo].[Main_table_UK] AS m
WHERE m.[Origin_Zip] = 'pr5 0xd'
AND m.[Trip Type] = 'roundtrip'
AND m.[Empties] = 'false'
AND datepart(year, convert(DATETIME2, m.[deliveryDate], 103)) = 2020
AND Unique_Column in (
SELECT Unique_Column FROM [dbo].[DB_TMS] where Load_Service_ID like '%LTL%')
GROUP BY m.[Origin_Zip], m.[Destination_Zip], m.[Load_Carrier_Description], m.[Load_Carrier_ID]
HAVING COUNT(*) >= 1;</s>
|
<s>[INST]Cannot Connect to SQL Availability Group Using ApplicationIntent = ReadOnly Get Network Error From Outside AWS
I have what I thought was a very simple Availability Group set up on two EC2 instances in AWS. There are two instances, one running on Windows Server 2016, and another running in Ubuntu 18.04. I created a cluster-less, domain-less Availability Group to allow for read-only queries to be routed to the secondary (Linux) server. Because it has no cluster (type=NONE), it really doesn't have a Listener, although I did create something like a dummy listener using the Private IP address of the primary (Windows) server. Then I set up Read-only routing on both servers.
Rather than DNS, I am depending on Hosts files on all the servers. The Listener and the primary server are set up with the same IP address in the Hosts files. I have a dummy domain as well, .DOMAIN, in the hosts files. It doesn't seem to matter
When I connect to the Availability group from a machine inside my AWS Security Group, I don't have any trouble attaching to the appropriate Availability Group database. The SQLCMD works as I supposed it would:
SQLCMD -S AG_LISTENER,1433 -U sa -P ********* -d AvailabilityDatabaseA -K ReadOnly -Q "SELECT @@SERVERNAME" returns 'LINUX-SQLHOST'
SQLCMD -S AG_LISTENER,1433 -U sa -P ********* -d AvailabilityDatabaseA -Q "SELECT @@SERVERNAME" returns 'WINDOWS-SQLHOST'
SQLCMD -S WINDOWS_SQLHOST,1433 -U sa -P ********* -d AvailabilityDatabaseA -K ReadOnly -Q "SELECT @@SERVERNAME" returns 'WINDOWS-SQLHOST'
Yet, when I attempt to attach using a Public IP (either the DNS AWS gave me or an Elastic IP) I get some strange behavior:
SQLCMD -S PUBLIC_IP_OF_WINDOWS_HOST,1433 -U sa -P ********* -d AvailabilityDatabaseA -Q "SELECT @@SERVERNAME" returns 'WINDOWS-SQLHOST'
SQLCMD -S PUBLIC_IP_OF_WINDOWS_HOST,1433 -U sa -P ********* -d AvailabilityDatabaseA -K ReadOnly -Q "SELECT @@SERVERNAME" times out, then gives a 'network-related or instance-specific error establishing a connection to SQL Server. Server is not found or not accessible.'
And strangely,
SQLCMD -S PUBLIC_IP_OF_LINUX_HOST,1433 -U sa -P ********* -d AvailabilityDatabaseA -K ReadOnly -Q "SELECT @@SERVERNAME" returns 'LINUX-HOST'
and
SQLCMD -S PUBLIC_IP_OF_LINUX_HOST,1433 -U sa -P ********* -d AvailabilityDatabaseA -Q "SELECT @@SERVERNAME" (no Read-Only Intent) returns an error 'the target database ('AvailabilityDatabaseA') is in an availability group and is currently accessible for connections when the application intent is set to read only.'
Is there some DNS hoodoo I need to attend to? That's what it seems like. I am not connecting to the 'Listener'.
[/INST]when I attempt to attach using a Public IP (either the DNS AWS gave me or an Elastic IP) I get some strange behavior:
>
> Is there some DNS hoodoo I need to attend to? That's what it seems like. I am not connecting to the 'Listener'.
Let me explain how read only routing works and then I think you'll understand since you've done a fairly good job investigating on your own.
When you setup read only routing you have an endpoint url and a routing list. The routing list is for the most part, ordinary, it lists who to go to and when, depending on various situations. The endpoint url, however, is the real key here. This is setup to point to a TDS endpoint (which is the protocol SQL Server uses to communicate to clients and other servers).
The TDS specification defines this behavior, so when read only routing is evaluated and the server decides that this connection is indeed good to be read only routing to a specific replica, it fills in the bits in the TDS packet to send back to the client saying that there will be an environment change, this is read only routing, and it's going to now go to the endpoint url that was previously configured.
Here's where you run into a problem as you have a private address and a public address. The routing url is most likely configured with the private address, which is what is passed directly back to the client driver. Let's make up some IPv4 addresses (works with IPv6 too), let's say the internal AWS address is 192.168.1.20 and the public address is 20.153.200.5 - great. If the routing url was configured with 192.168.1.20, then this will be passed back to the client driver, the client driver will then disconnect from the current connection to the primary and create a new connection with the exact url it was given, in this case 192.168.1.20. This works when you're inside your private area as this can be resolved quite easily. However, when you're outside AWS, say at your home without VPN or other items, the client driver will still get the same value and still try to connect to the same address, 192.168.1.20 - it's at this point, that's not going to resolve anywhere helpful and you will get the error you've been receiving.
There isn't a whole lot you can do... you can make your own host entries, aliases, etc., but if the internal servers can resolve the public address and you're going to use it from the outside more than internally, I'd make the routing url the public address.</s>
|
<s>[INST]Password Expiry for SQL Authenticated
Dear Experts,
If I mention "Enforce password expiration" for a SQL instance in a sql authenticated account and my local policy defines password expiry as 45 days as mentioned in secpol.msc in windows Local Security Policy , will I be unable to login to the SQL account after 45 days. This is for 2017 and 2019 Version
Thanks
[/INST]that is the purpose of password policy, you wouldn't be able to login unless you change your password. It is up to the application to let you change your password. Password policy for SQL logins has been available since SQL Server 2005.</s>
|
<s>[INST]Transaction log is full 9002 error
Hi SQLTeam,
Today we have been receiving continuous log full 9002 alerts. The drive is completely full with 10mb free space.
Identified an open transaction and associated sql statement which is been run from past 2 days and in sleeping mode doing nothing.
The database is in FULL recovery models and transaction log backup is scheduled every 1 hour, db size is around 3TB. Log file grown to 1TB.
Here are some clarifications I am looking for :
When transaction log is full,
1\) What happens for the incoming transactions for that particular database?
2) Are there any side affects when always on and log shipping is configured for this particular database ?
Thanks,
Bob
[/INST]Are there any side affects when always on and log shipping is configured for this particular database
For logshipping no assuming it is running properly. For AG yes. Now this largely depends on AG configuration, number of replicas and bandwidth and load on bandwidth between primary and secondary replica. For AG it is said you are only as fast as your slowest replica. So if everything is fast and your one of replica is slow it will slow the data flow hence causing log file to grow fast on primary.
EDIT:From your follow up question
> But question is, it was showing up AVAILABILITY_REPLICA" log_reuse_description for almost more than 5 hours.
2 Things
1. Large transaction of primary which is being sent to secondary and their is network latency
2. A blocked REDO on secondary.
My hunch is 2nd option. A large REDO or blocked REDO will not allow the REDO to complete instantaneously and may affect incoming transactions. See below thread</s>
|
<s>[INST]SQL if statemnt in visual basic
Hi Guys,
I'm trying to display different forms based on the value in the usertype field in the DB but I can't get it to work. I presume it's a problem with calling the table but I don't know where I'm going wrong.
Any help would be appreciated.
Thanks
Public Class Login
Private Sub BtnLogin_Click(sender As Object, e As EventArgs) Handles BtnLogin.Click
Dim con As SqlConnection = New SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\pdroz\Desktop\NewTrialApp\NewTrialApp\PiotrsAppDB.mdf;Integrated Security=True")
Dim cmd As SqlCommand = New SqlCommand("select * from LoginTable where username='" & Employeetxt.Text & "'and password='" & Password.Text & "'", con)
Dim sda As SqlDataAdapter = New SqlDataAdapter(cmd)
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
If (dt.Rows.Count > 0) Then
MessageBox.Show("You are logged in as " + dt.Rows(0)(2))
If (cmdusertype.value = "user") Then
Dim u As New user
u.Show()
Me.Hide()
ElseIf
(cmdusertype.value = "admin")
Dim a As New admin
a.Show()
Me.Hide()
Else
Dim m As New manager
m.Show()
Me.Hide()
End If
Else
MessageBox.Show("Error")
End If
End Sub
End Class
[/INST]Probably you must add something like *‘Dim usertype As String = dt.Rows(0)(3).ToString’*, with correct index instead of 3, then use *usertype* in next *Ifs* instead of *cmdusertype*.
By the way, because you are not using Parameterised Queries, an attacker can use your program without knowing the password.</s>
|
<s>[INST]SQL advise please
Hi
I have two tables StaffRequired and StaffBookedAggregate. Both have the following columns;
EventID, Role, StartTiem, EndTime, Qty
I need rows from StaffRequired that;
a. Do not have corresponding rows in StaffBookedAggregate for the combination EventID+Role+StartTime+EndTime, or
b. If there are corresponding rows in StaffBookedAggregate for the combination EventID+Role+StartTime+EndTime then StaffRequired.Qty > StaffBookedAggregate.Qty.
'b' is easy (I join both tables on EventID+Role+StartTime+EndTime columns and see if StaffRequired.Qty - StaffBookedAggregate.Qty > 0), but I am not sure how to do 'a' above. Can both 'a' and 'b' be done in a single query?
The idea is that I need to find out, for a given event which staff roles for given time ranges are not fully booked.
Thanks
Regards[/INST]a) can be achieved with an OUTER (e.g. LEFT) JOIN =>
SELECT SR.*
FROM StaffRequired AS SR
LEFT JOIN
StaffBookedAggregate AS SBA
ON SR.EventID = SBA.EventID
AND SR.Role = SBA.Role
AND SR.StartTime = SBA.StartTime
AND SR.EndTime = SBA.EndTime
WHERE SR.EventID IS NULL;</s>
|
<s>[INST]If i use SQL Server key name( like where , select, value ) as one of the column name in my user defined table, is there any performance impact ?
Hi Experts, In one of my table, i had column name "Value". but when i write any T-SQL statement by using that column, it is appeared as blue color since it is system defined keyword. so is there is any performance issue or other issues if I use SQL server key words as column names. Please provide me insights for this. Thanks in advance.[/INST]When you want to use sql server keywords as column names, you can use [],
for example:
[values]
in the form of [], it has no effect on performance.But it is not recommended to use sql server keywords as column names.</s>
|
<s>[INST]sql server 2019 developer edition
My company currently has Enterprise per core licensing on all servers, if i change the development servers to the Developer edition, do we need any license on the client side?
Thanks.
[/INST]\> Does that mean we cannot use the Developer Edition?
No. You can use the copy from production to developer for test purpose.
When you install SQL Server Developer Edition, the license terms are copied to a location like:
C:\Program Files\Microsoft SQL Server\150\License Terms\SQLServer2019_License_DEV_1033.rtf
You should read the license and apply it to your scenario.
The license states, in relevant part:
1. INSTALLATION AND USE RIGHTS.
a. General. You may install and use copies of the software on any device, including third party shared devices, to design, develop, test and demonstrate your programs. You may not use the software in a production environment.
b. Demonstration. Any person that has access to your internal network may install and use copies of the software to demonstrate use of your programs with the software. Those copies may not be used for any other purpose.
c. User Testing. Your end users may access the software to perform acceptance tests on your programs.</s>
|
<s>[INST]Column for bar code
Hi,
What kind of data type (of column) is for storing bar code?
[/INST]You could save your barcodes as datatype **CHAR(<number of characters>)** and not VARCHAR as VARCHAR is characters can vary in length and CHAR data does not.
If you're using actual product barcodes and they're really strings of 13 digits, a **char(13)** would probably be the most appropriate data type to store this data.
If you must store the graphical representation of the barcode for whatever reason, use a **VARBINARY(MAX)** field - gives you up to 2 GB of binary storage.</s>
|
<s>[INST]Select query from another database using 'exists'
Hello,
I hit an issue to get data using 'IN' operator from another database.
Could you please help me to fix it?
My query looks like this:
> SELECT i.EXTERNAL_CODE, tc.SITE_NAME, tr.TRANSACTION_DT
FROM app4_starlims_data.dbo.INVENTORY i
JOIN app4_starlims_data.dbo.VA_TUBE_COLLECTION tc
ON tc.INVENTORYID = i.INVENTORYID
JOIN app4_starlims_data.dbo.INVENTORY_TRANSACTIONS it
ON it.INVENTORYID = i.INVENTORYID
JOIN app4_starlims_data.dbo.transactions tr
ON tr.TRANSACTION_ID = it.TRANSACTION_ID
WHERE i.EXTERNAL_CODE IN
(SELECT vacutainer_ref, quality, \[timestamp\]
FROM dna_lab_biospecimen.dbo.blood_sample
WHERE quality LIKE '%under%'
AND \[timestamp\] BETWEEN '02-19-2021' AND '03-07-2021')
Thanks
[/INST]The issue is because within IN statement it is exepecting multiple values of a single column and not multiple columns.
SELECT vacutainer_ref, quality, [timestamp]
FROM dna_lab_biospecimen.dbo.blood_sample
WHERE quality LIKE '%under%'
AND [timestamp] BETWEEN '02-19-2021' AND '03-07-2021
So rather than having 2 columns use union statement and seperate columns as
Select c1 from t1
union
Select c2 from t2</s>
|
<s>[INST]Need Trigger for Updating .
i have data in table
Create table #tbl_GRN_Detail (D_ID int,GRN_ID int,item_code int,Issue_ID int)
Insert into #tbl_GRN_Detail values (11001,2001,22,Null)
Now i want ,when i insert row into #tbl_issuance ,then Issue_ID value get updated into #tbl_GRN_Detail col Issue_ID
Create table #tbl_issuance (issue_ID int,item_code int,Issue_Date int,D_ID int)
Insert into #tbl_issuance values (101,22,'2021-06-28',11001)
[/INST]Create table tbl_GRN_Detail (D_ID int,GRN_ID int,item_code int,Issue_ID int)
Insert into tbl_GRN_Detail values (11001,2001,22,Null)
Create table tbl_issuance (issue_ID int,item_code int,Issue_Date date,D_ID int)
go
CREATE TRIGGER issuance_tri ON tbl_issuance AFTER INSERT AS
UPDATE tbl_GRN_Detail
SET Issue_ID = i.issue_ID
FROM tbl_GRN_Detail G
JOIN inserted i ON G.D_ID = i.D_ID
go
Insert into tbl_issuance values (101,22,'2021-06-28',11001)
go
SELECT * FROM tbl_GRN_Detail
go
DROP TABLE tbl_GRN_Detail
DROP TABLE tbl_issuance
In a trigger, you have access to the virtual tables `inserted` and `deleted`. `inserted` holds the inserted rows by an INSERT statement and an afterimage of the rows for an UPDATE statement.</s>
|
<s>[INST]MAP error; backup file is not compatible...
Hi Microsoft,
For years I was able to open .BAK files created by this specific customer. Now when I try to open a .BAK with the same newest version of MAP Toolkit 9.9.13.0 as it also was installed on the customer site, I get the following error;
"A failure occurred while importing the database. Refer to the log file for more details. The specified backup file is not compatible with the version of SQL server currently running. Please use a backup file that is compatible with this version."
The customer confirmed that during the inventory wizard they checked exactly the same checkboxes as last year. Could you please:
- Send me a list of possible causes of this error divided by things to ckeck on our (Crayon) site and on the customers site?
I'm looking forward to your reply.
Regards,
Jordy
[/INST]I can't comment on the MAP aspects, but the error message is clear. You try to restore a SQL Server backup that was taken on a SQL Server which has a higher version than the one you try to restore to. Using backup and restore you can go up in version, but not down.</s>
|
<s>[INST]Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
Hi Team,
We are getting below error while running query in SSMS:
Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
Normally it shouldm't take more than 2 mins. But from yesterday onwards, the query failing with above error.
It is SQL Server 2016 With SP2 (CU17)[/INST]SSMS waits forever for a query to complete. If you get this error, this is because you have set a query timeout under Tools->Options->Query Execution->SQL Server->General->Execution time-out. You can also change it for the current window, by right-clicking and selecting Query Options from the bottom of the context menu. Set the time-out to 0 to wait forever.
As for why the query is running slower than yesterday... Well, have you investigated if it may be due to blocking? Else it is not unheard of that the execution plan changes, because of updated statistics or some other reason. And sometimes when the optimizer takes a wrong bet, the query can be a lot slower.
Do you have Query Store enabled on the database?</s>
|
<s>[INST]Calculating the completion rates within the same month
Hi All,
Hope you are doing well..I am trying to calculated the (percentage of) number of escalations that were completed in the same month they were raised.. The combination of ctextid and vbill denotes an escalation ..Raised denotes the datetime they were raised and resolved denotes the date time they were resolved... if resolved is null then the escalation is not yet resolved yet..Please find below the DDL for the input and output tables
**Input table**
create table ##input
(ctext int,
vbill int,
raised datetime2,
resolved datetime2)
insert into ##input values
('12','431','11/23/2020 0:41','11/23/2020 11:07'),
('13','432','12/3/2020 6:47','01/7/2021 9:59'),
('14','433','11/19/2020 5:12','11/19/2020 6:55'),
('15','434','11/9/2021 6:00','NULL'),
('16','435','12/24/2020 22:00','12/25/2020 11:16'),
('17','436','11/24/2020 21:01','11/25/2020 8:35'),
('18','437','12/2/2020 21:58','12/3/2020 7:25'),
('19','438','11/26/2020 1:59','12/26/2020 8:00'),
('20','439','11/24/2020 23:19','NULL'),
('21','440','12/29/2020 23:32','01/15/2021 9:02')
**Output table**
create table ##output
(timeframe varchar(40),
countofescalationsraised int,
countofescalationsresolvedinsamemonth int,
percentageofescalationsresolvedinsamemonth)
insert into ##output values
('44136','6','3','50'),
('44166','4','2','50'),
Thanks,
Arun
[/INST]Try one of queries:
; with Q as
(
select year(raised) as y, month(raised) as m,
count(raised) as raised,
count(case when year(raised) = year(resolved) and month(raised) = month(resolved) then 7 end) resolved
from ##input
group by year(raised), month(raised)
)
select
datediff(day, '1900-01-01', DATEFROMPARTS(y, m, 3)) as timeframe,
raised as countofescalationsraised,
resolved countofescalationsresolvedinsamemonth,
resolved * 100 / raised as percentageofescalationsresolvedinsamemonth
from Q
where raised <> 0 and resolved <> 0</s>
|
<s>[INST]Do Idle Sessions use Resources
I am a data analyst/report developer for a very large company. I use SSMS daily. I only have access to certain data; no access to the server, explain plan, or anything like that. The first thing I do each day is to open a copy of SSMS in which I create several global temp tables. Those temp tables provide the data necessary for several tabs in an Excel report. I also leave that copy of SSMS open throughout the day so the data in the temp tables is readily available for ad hoc reporting. This is not and has never been an issue.
Throughout the day I usually have at least one more copy of SSMS open with at least one query window, and typically three or four windows, open. I use that copy of SSMS to perform research and analysis for report development. Recently, I have been contacted by one of the DBAs telling me that I have a long running session and asking me to close it.
The situation is this: I open a session and run a query, which may finish in under a minute or take fifteen minutes or longer, but rarely do I let anything run over 30 minutes. I leave the session open - maybe I copy the results to Excel to analyze the data or I just move on to another window/session to do some more research. In the afternoon, I rerun the query in the session that I've had open since morning. While the query is running, the DBA contacts me and tells me the session has been open too long and is holding up resources.
Nothing is ever said about the ten sessions that remain open in my first open copy of SSMS. The DBA only contacts me if I am running a query in a session that has been open a long time (again - not a long running query but a query running in a long open session).
Question: Does that session pose any problem for the server during the time it is idle? Does the query that is running later in the day in that session use any more resources than the first time it ran?
Thank you very much,
Gregory[/INST]An open query window in SSMS does take up some resources, particularly there is an amount of memory allocated for the connection. However, for a single or even ten connections, this is nothing the DBA should worry about. When this can be a problem is if an application leaves thousands of connections open.
You say that you fill up temp tables in your first session. These temp tables take up space in tempdb, and if they are several gigabytes in size, the DBA may be concerned. Whether he/she should be concerned, I don't want to make a judgement of with the little I know at this point.
What absolutely can be a problem is if you do:
BEGIN TRANSACTION
-- Do something
and never commit that transaction. You would be holding locks that could block other users. But there can be problem even if you would only operate on your private tables, since that open transaction log prevents the transaction log from being truncated.
There is actually an option in SSMS that can help you to make friends with the DBA. Tools->Options->Query Execution->SQL Server->Advanced->Disconnect after the query executes. However, if you disconnect, you would lose those temp tables, so it does not sound like it would suit you.
As SimpleSamples say, you need to work with the DBA. Maybe there is a real problem that the DBA has not been able to communicate clearly, or which did not register with you, because you may not have the technical understanding to SQL Server to grasp it. Or maybe the DBA is just over-zealous. All this is hard to tell from a distance.</s>
|
<s>[INST]How to extract date from a long string
Hi All,
have a long string like below in my column and I need to extract only the date (2021-07-05) from it.
Could any one please help
Name - Koteswararao vp Department - Prod Location - Hyderabad Domain - ND Job Title - Technical-ABAP Date of Hire - 2021-07-05 Vendor ID - v2345 Candidate ID - Associate ID - 3334 Name - Hardware Allocation [/INST]Is it always the same ODBC format yyyy-MM-dd? Then this should work:
declare @string varchar(200) = 'Name - Koteswararao vp Department - Prod Location - Hyderabad Domain - ND Job Title - Technical-ABAP Date of Hire - 2021-07-05 Vendor ID - v2345 Candidate ID - Associate ID - 3334 Name - Hardware Allocation';
select substring(@string, PATINDEX('%20[0-9][0-9]-[0-1][0-9]-[0-3][0-9]%', @string), 10)</s>
|
<s>[INST]How to encrypt table name and column name in sql server?
Hi All,
I know column data can be encrypted in sql server. But can anyone please help how can i encrypt table name and column name in sql server.
Thanks
Chirag[/INST]how can i encrypt table name and column name in sql server.
And what's that good for?
You can create views on the base table and in the view you can define cryptic alias name for the column to "obfuscated" their content/intent.
Grant the user only access on the views, but not on the base tables.</s>
|
<s>[INST]THe Transaction log for database is full
Hello,
I been facing below error from last two days.
I took full backup and Transaction log backup after that but still some SQL jobs has been failing with below error.
Error :- The transaction log for database 'DB' is full due to 'LOG_BACKUP'. [SQLSTATE 42000] (Error 9002). The step failed.
Drive is empty where we save our logs files at.
What should causing this?
[/INST]I can't say how large your log files has to be, but they are now extremely small compared to the database size. Perhaps start by having just one log file and make it some 20% of the data size, as a starting point. The configure a reasonable autogrow fot hat log file. Not pecentage. Perhaps 1 GB, as a staring point. And don't shrink the log file (in case you do).</s>
|
<s>[INST]Can one use a where clause inside a partition clause?
Is there a way to add a where clause when doing a partition?
I have several columns and want to add 2 more column whereby I will only count total status for each origin and Total red status where status color = red only.
Create table #Temp
(
Origin_ID INT
,Origin_Name VARCHAR(3)
,Status_ID INT
,Status_Color VARCHAR(10)
)
Go
Insert into #Temp Values (2, ‘RCO’, 1, ‘Red’)
Insert into #Temp Values (2, ‘RCO’, 2, ‘Red’)
Insert into #Temp Values (2, ‘RCO’, 3, ‘Green’)
Insert into #Temp Values (2, ‘RCO’, 3, ‘Red’)
Insert into #Temp Values (3, ‘USA, 1, ‘Red’)
Insert into #Temp Values (3, ‘USA’, 2, ‘Green’)
Insert into #Temp Values (4, ‘CAN’, 1, ‘Green’)
SELECT DISTINCT Origin_ID, Origin_Name
,Count(Status_ID) Over (Partition by Origin_ID Order by Origin_ID) Total_status_count
--how do i calculate the Total Red_status_count only
From #Temp
Origin_ID Origin_name Total_Status_count Total_red_status
2 RCO 4 3
3 USA 2 1
4 CAN 1
[/INST]You could also try with **SUM** as below:
SELECT DISTINCT Origin_ID, Origin_Name,
Count(Status_ID) AS Total_status_count,
SUM(CASE WHEN Status_Color = 'Red' THEN 1 ELSE 0 END) AS Red_count
From #Temp
GROUP BY Origin_ID, Origin_Name
ORDER BY Origin_ID
OR
SELECT DISTINCT Origin_ID, Origin_Name,
Count(Status_ID) Over (Partition by Origin_ID Order by Origin_ID) Total_status_count,
SUM(CASE WHEN Status_Color = 'Red' THEN 1 ELSE 0 END) Over (Partition by Origin_ID Order by Origin_ID) Red_count
From #Temp
ORDER BY Origin_ID
Output:
Origin_ID Origin_Name Total_status_count Red_count
2 RCO 4 3
3 USA 2 1
4 CAN 1 0
By the way, the count of 'red' for 'CAN' could be 0 based on your sample data. Please help check again.</s>
|
<s>[INST]Clear the cache while Stored Procedure session is running
What happen if a SP A is running slowly with 5 different session ID (executed 5 times) and that point of a time, I clear the cache of that SP A or I execute sp_recompile for that SP A. Is it all the 5 session ID which is running SP A will start again with different plan or it's still executing using the same execution plan which previously it used before clear the cache ? [/INST]Is it all the 5 session ID which is running SP A will start again with different plan or it's still executing using the same execution plan which previously it used before clear the cache
Clearing a cache, in your case to be precise procedure cache, will not affect already running queries. When you execute a query it is compiled and plans are generated and the most cost effective plan is selected and stored, post this query is run by sql server based on the plan. Clearing the cache removes the plan but will not affect already running queries. But, a new SP execution request will now first create new plan and then run it.</s>
|
<s>[INST]Adding a tuple from a function to table
Hi,
I am creating a function and I want it to add a tuple from the function to a table-as the question says above :'D-
I got the function right but I am missing something...I am missing the part of
RETURNS
What should I write after RETURNES keyword ? I want to add a tuple -let's say I want to add The Employee_id , Employee_name, Spec-
How can I return these values into the table ?
Thanks in advance,[/INST]I'm not sure that I understand your question. In your function definition you insert any data to a table, but you can do that when you use the function.
Here is an example of an inline table-valued function:
CREATE FUNCTION dbo.inline(@n int) RETURNS TABLE AS
RETURN (SELECT object_id, name FROM sys.objects WHERE object_id % @n = 0)
Here is the same function as a multi-statement function:
CREATE FUNCTION dbo.multistmt(@n int)
RETURNS @t TABLE (object_id int NOT NULL,
name sysname NOT NULL) AS
BEGIN
INSERT @t(object_id, name)
SELECT object_id, name FROM sys.objects WHERE object_id % @n = 0
RETURN
END
Here are examples of calling them and inserting data into a table:
CREATE TABLE #test (object_id int NOT NULL,
name sysname NOT NULL)
go
INSERT #test (object_id, name)
SELECT object_id, name FROM dbo.inline(5)
INSERT #test (object_id, name)
SELECT object_id, name FROM dbo.multistmt(7)</s>
|
<s>[INST]how to distinct parent tag in for xml path in sql server
CREATE TABLE temp_xmltable1(
Report_id INT,
Report_name VARCHAR(6),
Report_Gender VARCHAR(1),
Report_DOB DATETIME,
Transaction_number INT,
Transaciont_code VARCHAR(2),
Amount INT,
Currency\` VARCHAR(3)
);
INSERT INTO temp_xmltable1 VALUES
(1,'Karthi','M','2021-09-03 00:00:00',1001,'AC',2000,'IND'),
(1,'Karthi','M','2021-09-03 00:00:00',1002,'IB',4000,'USD'),
(1,'Karthi','M','2021-09-03 00:00:00',1003,'IB',6000,'GBP');
I need output like below xml format
\<report>
\<Report_id>1\</Report_id>
\<reporting_person>
\<Report_name>Karthi\</Report_name>
\<Report_Gender>M\</Report_Gender>
\<Report_DOB>09-03-21\</Report_DOB>
\</reporting_person>
\<transaction>
\<Transaction_number>1001\</Transaction_number>
\<Transaciont_code>AC\</Transaciont_code>
\<Amount>2000\</Amount>
\<Currency>IND\</Currency>
\</transaction>
\<transaction>
\<Transaction_number>1002\</Transaction_number>
\<Transaciont_code>IB\</Transaciont_code>
\<Amount>4000\</Amount>
\<Currency>USD\</Currency>
\</transaction>
\<transaction>
\<Transaction_number>1003\</Transaction_number>
\<Transaciont_code>IB\</Transaciont_code>
\<Amount>6000\</Amount>
\<Currency>GBP\</Currency>
\</transaction>
\</report>
[/INST]Please try the following solution.
**SQL**
-- DDL and sample data population, start
DECLARE @tbl TABLE (
Report_id INT,
Report_name VARCHAR(6),
Report_Gender VARCHAR(1),
Report_DOB DATETIME,
Transaction_number INT,
Transaciont_code VARCHAR(2),
Amount INT,
Currency VARCHAR(3)
);
INSERT INTO @tbl VALUES
(1,'Karthi','M','2021-09-03 00:00:00',1001,'AC',2000,'IND'),
(1,'Karthi','M','2021-09-03 00:00:00',1002,'IB',4000,'USD'),
(1,'Karthi','M','2021-09-03 00:00:00',1003,'IB',6000,'GBP');
-- DDL and sample data population, end
SELECT Report_id
, Report_name AS [reporting_person/Report_name]
, Report_Gender AS [reporting_person/Report_Gender]
, TRY_CAST(Report_DOB AS DATE) AS [reporting_person/Report_DOB]
, (SELECT Transaction_number
, Transaciont_code
, Amount
, Currency
FROM @tbl
FOR XML PATH('transaction'), TYPE)
FROM @tbl
GROUP BY Report_id, Report_name, Report_Gender, Report_DOB
FOR XML PATH('report'), TYPE;
**Output**
<report>
<Report_id>1</Report_id>
<reporting_person>
<Report_name>Karthi</Report_name>
<Report_Gender>M</Report_Gender>
<Report_DOB>2021-09-03</Report_DOB>
</reporting_person>
<transaction>
<Transaction_number>1001</Transaction_number>
<Transaciont_code>AC</Transaciont_code>
<Amount>2000</Amount>
<Currency>IND</Currency>
</transaction>
<transaction>
<Transaction_number>1002</Transaction_number>
<Transaciont_code>IB</Transaciont_code>
<Amount>4000</Amount>
<Currency>USD</Currency>
</transaction>
<transaction>
<Transaction_number>1003</Transaction_number>
<Transaciont_code>IB</Transaciont_code>
<Amount>6000</Amount>
<Currency>GBP</Currency>
</transaction></s>
|
<s>[INST]Execute SQL commands stored in database column
I have a small bit of SQL that creates a temporary table, #List, with a column "Command".
The contents of the Command column are SQL commands ready to execute.
I'm beating my head against a wall, trying to: run through the table, one row at a time, executing the contents of the column. Anyone have any advice?
Thanks,[/INST]You can do this:
DROP TABLE IF EXISTS #List
CREATE TABLE #List (Command varchar(max), OrderBy INT IDENTITY(1,1))
INSERT INTO #List VALUES
('SELECT * FROM Table1'),
('SELECT * FROM Table2'),
('DELETE FROM Table1'),
('SELECT * FROM Table1')
DECLARE @sqlcmd VARCHAR(MAX);
SET @sqlcmd = (
SELECT STRING_AGG(Command,';' + CHAR(10)) WITHIN GROUP (ORDER BY [OrderBy]) as cmd
FROM #List
)</s>
|
<s>[INST]select Json related value and revert option
I Hi,
I want one more changes
i want display Name related ID
--Query1--
create table #CIDValue (Slno int,CID varchar(100))
INSERT INTO #CIDValue (Slno,CID) VALUES (67,'AAA'),(68,'BBB'),(69,'CCC')
create table #temp (ID INT,Details nvarchar(200))
INSERT INTO #temp (ID,Details) VALUES (1001,'[{"CID":"CCC"}]'),
(1002,'[{"CID":"AAA"},{"CID":"BBB"},{"CID":"CCC"}]'),
(1003,'[{"CID":"AAA"},{"CID":"BBB"},{"CID":"CCC"}])')
select * from #temp
drop table #temp,#CIDValue
--I want result like below
--ID Details
--1001 69
--1002 67,68,69
--1003 67,68,69
--Query2--
create table #CIDValue1 (Slno int,CID varchar(100))
INSERT INTO #CIDValue1 (Slno,CID) VALUES (67,'AAA'),(68,'BBB'),(69,'CCC')
create table #temp1 (ID INT,Details nvarchar(200))
INSERT INTO #temp1 (ID,Details) VALUES (1001,'69'),
(1002,'67,68,69'),
(1003,'67,68,69')
select * from #temp1
drop table #temp1,#CIDValue1
--I want result like below
--ID Detail
--1001 [{"CID":"CCC"}]
--1002 [{"CID":"AAA"},{"CID":"BBB"},{"CID":"CCC"}]
--1003 [{"CID":"AAA"},{"CID":"BBB"},{"CID":"CCC"}])
pls help[/INST]Try these queries:
select ID, string_agg(c.Slno, ',') as Details
from #temp
cross apply openjson( Details, '$') with ( v varchar(max) '$.CID' )
inner join #CIDValue c on c.CID = v
group by ID
select ID, concat( '[', string_agg( j, ','), ']') as Details
from #temp1
cross apply string_split(Details, ',') s
inner join #CIDValue1 c on c.Slno = s.value
cross apply (values ((select c.CID as CID for json path, without_array_wrapper))) t(j)
group by ID
You can also discover that there are equivalent functions for *STRING_AGG* and *STRING_SPLIT* for old versions of SQL servers.</s>
|
<s>[INST]Log growth in simple recovery model
My database is in simple recovery mode and log is growing very fast and space in disk is very less. There are 2 transaction is running in My database and the first transaction is running 20 mins earlier than second transaction. Both transaction still running and didn't release the log space due to active transaction. When i check, i found out that second transaction using more logs than first transaction eventhough first transaction started first. In this case, can i kill second transaction which using more log space to free up some space or i must kill the oldest transaction first which is first transaction to release log space.
[/INST]The transaction log will never be truncated past the oldest active transaction. That transaction may have been left orphaned and is doing nothing, but that does not matter. SQL Server is not able to selectively delete log space for committed transaction, so it has to keep the entire log so that it can roll back this open transaction if needed.</s>
|
<s>[INST]Call SQL Agent Job on different instance
I have a SQL Job on a 2008 R2 instance and would like as it's final step to start another SQL job on a SQL 2019 instance. Is this possible?[/INST]You can set up a CmdExec job that connects with SQLCMD to the other instance and runs sp_start_job. You would have create a proxy user that has permissions to start jobs on the other instance, and you would select this user as Run As for the job.</s>
|
<s>[INST]How to retrieve actual query plan for a specific stored procedure using Extended Events?
Is there an example of how to define an extended event that will capture the actual query plan for a single / specific stored procedure each time it executes?
[/INST]You could probably to this by setting up an event session with the appropriate filters.
BUT DON'T DO THIS! At least not in production.
If you create an event session with any of the events that captures the actual execution plan, all process will start to generate query plans, no matter the filtering. This is because the payload for the event is created first, before the filtering.
When I have tested this with a workload that runs an optimised cursor (that is, many, short-running statements), I have seen performance penalty of a factor 12!
If you really need to do this, use good ol' Trace instead. In my tests, the performance penalty was "only" a factor of 3.
What is the actual problem you are trying to solve.</s>
|
<s>[INST]Finding the distinct number of coders and number of encounters completed per day
Hi All,
Hope you are doing well!... A combination of contextid and visitbillid represents an encounter ...An encounter can be 1) Just coded by one person and then completed 2) coded by one person and then qaed by another person and then completed...
1\) I am trying to identify the distinct count of coders (both coders and qa coders) who have coded on a particular day and the number of encounters completed on a day denoted by the completed field
2\) I am trying to identify the distinct count of coders who have coded in a particular completed month and the number of encounters completed in that month...
Please find the DDL below for the input table and the output table 1 and output table 2...can you please help me here..
## Input
create table ##input
(contextid int,
visitbillid int,
completed datetime2,
codedby varchar(20),
qaby varchar(20)
)
insert into ##input values
('561','21','1/10/2021 11:43:03 PM','ca3','ca5'),
('561','178','1/10/2021 9:43:03 AM','ca4',''),
('451','213','1/10/2021 10:30:03 AM','ca5','ca6'),
('312','2','1/11/2021 11:43:03 AM','ca3','ca2'),
('312','12','1/11/2021 9:43:03 PM','ca6',''),
('211','134','1/11/2021 5:30:03 PM','ca5','ca1'),
('214','231','1/12/2021 3:30:03 PM','ca4','ca2'),
('234','111','1/12/2021 3:30:03 PM','ca5',''),
('345','121','1/12/2021 3:30:03 PM','ca2','ca3'),
('443','789','2/1/2021 3:30:03 PM','ca4','ca1'),
('211','991','2/1/2021 3:59:03 PM','ca1',''),
('331','2131','2/2/2021 3:59:03 PM','ca5','ca2'),
('1071','321','2/2/2021 6:59:03 PM','ca2','ca6'),
('777','121','2/10/2021 6:59:03 PM','ca4','ca1'),
('1231','1211','2/10/2021 6:59:03 PM','ca1','ca6')
## output1
create table ##output1
(completed date,
distinctnumberofcoders int,
numberofcompletedvisitbills int
)
insert into ##output1 values
('1/10/2021','4','3'),
('1/11/2021','5','3'),
('1/12/2021','4','3'),
('2/1/2021','2','2'),
('2/2/2021','3','2'),
('2/10/2021','3','2')
## output2
create table ##output2
(completed date,
distinctnumberofcoders int,
numberofcompletedvisitbills int
)
insert into ##output2 values
('1/1/2021','6','9'),
('2/1/2021','5','6')
Thanks,
Arun
[/INST]Check these queries (for SQL Server):
;
with Q1 as
(
select contextid, visitbillid, cast(completed as date) as completed, codedby as coder
from ##input where codedby <> ''
union all
select contextid, visitbillid, cast(completed as date) as completed, qaby as coder
from ##input where qaby <> ''
)
select completed,
count(distinct coder) as distinctnumberofcoders,
count(distinct visitbillid) as numberofcompletedvisitbills
from Q1
group by completed
 
;
with Q1 as
(
select contextid, visitbillid, datefromparts(year(completed), month(completed), 1) as completed, codedby as coder
from ##input where codedby <> ''
union all
select contextid, visitbillid, datefromparts(year(completed), month(completed), 1) as completed, qaby as coder
from ##input where qaby <> ''
)
select completed,
count(distinct coder) as distinctnumberofcoders,
count(distinct visitbillid) as numberofcompletedvisitbills
from Q1
group by completed</s>
|
<s>[INST]Restoring SQL Server Database from Drive Image backup
Hi,
My company runs a database application with MS Access as the front end and MS SQL Server as the back end. I am planning to execute some code that will make changes to a quite a bit of data. This code has not been thoroughly tested. I hope that it will work fine, but if it doesn't produce the desired results, it would be difficult for me to manually reverse all the changes made. For this reason, I am planning to execute the code only after I know that we have a current backup. If the code causes problems, I'd like to restore the database from my backup.
The way that the server computer is backed up is periodic drive image. The person (outside IT guy) who manages the server for us says that he has drive imaging software that automatically saves a drive image every hour. He says he can restore any files or folders from the drive image backup with a simple file copy process.
My question is, can a SQL server database be properly restored by simply copying some files and folders to the right location? Or is it more complicated than this?
Thanks in advance,
Paul[/INST]You could restore the database that way, but it sounds a bit complicated, because you would have take the database offline and move the files back in place.
And, overall, I would not rely on image-based backups for business-critical databases, but use the built-in BACKUP commands. What you describe may be OK for less critical databases running in simple recovery where some data loss can be accepted in case of a disaster.
In your case, I would recommend that you take a manual backup:
BACKUP DATABASE db TO DISK = 'c:\temp\db.bak' WITH INIT, COMPRESSION, COPY_ONLY
If something goes wrong, you do:
USE tempdb
go
ALTER DATABASE db SET SINGLE_USER WITH ROLLBACK IMMEDIATE
RESTORE DATABASE db FROM DISK = 'c:\temp\db.bak'
ALTER DATABASE db SET MULTI_USER
go
You should also make sure that no one else is using the database while you are running your script, so that they don't lose work when you restore.</s>
|
<s>[INST]JSON - multiple aggregations extremely slow
Select col1
,sum(json_value(json_field,’$.col2’))
,sum(json_value(json_field,’$.col3’))
,sum(json_value(json_field,’$.col4’))
,sum(json_value(json_field,’$.col5’))
,avg(json_value(json_field,’$.col6’))
,max(json_value(json_field,’$.col7’))
From table1
Group by col1
The table has 78000 rows. Json_field has a json structure with 600 attributes. When I perform just one aggregation it takes less than 1 sec. The performance degrades with addition of each aggregation. The query takes 17 seconds which is not acceptable. When I perform each aggregation on its own the six queries finish in 6 sec. This tells me there is repeated parsing happening with each additional json_value.
I am new to json in sql server. Any help here would be of great value.
Thanks![/INST]Try two other possibilities:
select col1,
sum(json_value(j, '$.col2')),
sum(json_value(j, '$.col3')),
from Table1
cross apply (values (json_query(json_field, '$'))) t(j)
and
select col1,
sum(col2),
sum(col3),
from Table1
cross apply openjson(json_field) with
(
col2 int '$.col2',
col3 int '$.col3',
)</s>
|
<s>[INST]Finding the overall Utilization by month of claim creation
Hi All,
Hope you are doing well!...I am trying to build a dataset that calculates the number of clients (distinct count of (ctextid,prid) by month of claim creation -> claimcreated field) and the utilization (number of claims created by organizationid other than PRACTICE divided by the total number of claims created (by PRACTICE and other vendors).. The claim created is at the level of (ctextid->prid->claimid)... I want to do all reactions by month of claim creation ->( claimcreated).....Please find the input and output DDL below... Can you please help me here...
**INPUT**
create table input
(ctextid int,
prid int,
claimid int,
claimcreated datetime2,
organizationid varchar(50),
)
insert into input values
('788','91','211','9/16/2021 4:59:18 PM','PRACTICE'),
('788','91','121','9/28/2021 10:32:33 PM','PRACTICE'),
('788','91','311','9/7/2021 8:22:40 PM','PRACTICE'),
('788','91','579','9/8/2021 5:52:27 AM','OG'),
('788','91','637','9/17/2021 11:14:20 AM','ACE'),
('788','91','87638','10/23/2021 12:34:00 AM','OG'),
('788','91','71395','10/20/2021 10:07:31 PM','PRACTICE'),
('788','91','133216','10/17/2021 4:02:15 AM','ACE'),
('788','91','29823','10/25/2021 4:06:38 PM','PRACTICE'),
('788','91','522','10/4/2021 10:51:53 AM','PRACTICE'),
('788','91','23728','10/27/2021 9:25:23 AM','ACE'),
('902','83','832','9/20/2021 10:32:33 PM','PRACTICE'),
('902','83','836','9/28/2021 10:32:33 PM','PRACTICE'),
('902','83','932','9/24/2021 10:32:33 PM','PRACTICE'),
('902','83','567','10/24/2021 10:32:33 PM','OG'),
('902','83','321','10/27/2021 10:32:33 PM','ACE'),
('902','83','2312','10/21/2021 10:32:33 PM','ACE')
('567','27','3111','10/5/2021 10:32:33 PM','PRACTICE'),
('567','27','3131','10/7/2021 10:32:33 PM','OG'),
('775','456','221','10/15/2021 10:32:33 PM','ACE'),
('775','489','900','10/18/2021 10:32:33 PM','PRACTICE')
('999','121','78','8/18/2021 10:32:33 PM','PRACTICE'),
('998','1341','889','8/4/2021 10:32:33 PM','OG'),
('965','671','212','8/7/2021 10:32:33 PM','ACE')
OUTPUT
create table output
(yearmonth varchar(40),
utilization int,
noofclients int)
insert into output values
('Aug-21','Sep-21','Oct-21'),
('67','25','62'),
('3','2','5')
Output below:
yearmonth Aug-21 Sep-21 Oct-21
utilization 67 25 62
noofclients 3 2 5
Thanks,
Arun
[/INST]Check if this query corresponds:
drop table if exists #local
;
with Q as
(
select *, eom = EOMONTH(claimcreated)
from input
)
select
eom,
[month] = format(eom, 'MMM"-"yyyy'),
utilization = count(case when organizationid <> 'PRACTICE' then 1 end) * 100 / count(organizationid),
noofclients = (select count(*) from (select distinct ctextid, prid from Q where eom = t.eom) d)
into #local
from Q t
group by eom
declare @cols varchar(max) =
stuff((select ', ' + quotename(month) from #local order by eom for xml path('')), 1, 2, '')
declare @sql varchar(max) = concat(
'select ''utilization'' as [ ], *
from ( select month, utilization from #local) t
pivot ( max(utilization) for month in (', @cols, ')) p
union all
select ''noofclients'', *
from ( select month, noofclients from #local) t
pivot ( max(noofclients) for month in (', @cols, ')) p'
)
exec (@sql)
/*
Aug-2021 Sep-2021 Oct-2021
utilization 66 25 61
noofclients 3 2 5</s>
|
<s>[INST]For every CarID calculate mode of Price within specific date range
Hello there, i stuck in problem - Calculate mode Price within specific date range (e.i 2020-21). I think, i was done with the first part of task, but exist next additional condition - "if you have more than one mode, display average price of all modes".
SELECT Price AS ModePrice, COUNT() AS Count
FROM CARDATABASE
GROUP BY Price
HAVING COUNT() >= ALL (SELECT COUNT(*) FROM CARDATABASE GROUP BY Price
[/INST],
Please also check:
SELECT Price AS ModePrice,
COUNT() OVER(PARTITION BY Price )AS Count,
AVG(Price) OVER(PARTITION BY CarID) AS averagevalue
FROM CARDATABASE
If you have any question, please feel free to let me know.</s>
|
<s>[INST]Sysadmin - rights to write, modify and drop on all databases?
Short question:
-Does Sysadmin has the rights to write, modify and drop on all databases that exist on a SQL server?
-Really appreciate your answer
[/INST]Members of the server role SysAdmin have all unlimited permissions on SQL Server and can do everything on server and database level.</s>
|
<s>[INST]Column 'result.result_id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
I have a query that I have created, when I run it I get these errors:
Msg 8120, Level 16, State 1, Line 7
Column 'result.result_id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
select
MAX(p.patient_name) 'Dogs Name',
MAX(rq.print_note) 'Vial #',
MAX(rq.collect_date) 'Collect Date',
(select result from result r2
where panel_test_id = '1196'
and r.result_id = r2.result_id) 'Cortisol (ug/dL)',
(select result from result r2
where panel_test_id = '1197'
and r.result_id = r2.result_id) 'Creatinine (mg/dL)',
(select result from result r2
where panel_test_id = '1195'
and r.result_id = r2.result_id) 'UC:Cr (Ratio)'
from result r
left join req_panel rp
on r.req_panel_id = rp.req_panel_id
left join requisition rq
on rp.requisition_id = rq.requisition_id
left join vw_patient p
on rq.patient_eid = p.patient_eid
Where panel_test_id in ('1196','1197','1195')
group by rp.req_panel_id
order by 3 desc
[/INST]I think is what you might be looking for. But note that since I don't have your tables, it is a bit of a guessing game:
select (p.patient_name) 'Dogs Name',
(rq.print_note) 'Vial #',
(rq.collect_date) 'Collect Date',
r."Cortisol (ug/dL)", r."Creatinine (mg/dL)", r."UC:Cr (Ratio)"
from (select req_panel_id,
min(case when panel_test_id = '1196' then result end) AS "Cortisol (ug/dL)",
min(case when panel_test_id = '1197' then result end) AS "Creatinine (mg/dL)",
min(case when panel_test_id = '1195' then result end) AS "UC:Cr (Ratio)"
from result
Where panel_test_id in ('1196','1197','1195')
group by req_panel_id) as r
left join req_panel rp
on r.req_panel_id = rp.req_panel_id
left join requisition rq
on rp.requisition_id = rq.requisition_id
left join vw_patient p
on rq.patient_eid = p.patient_eid
ORDER BY "Collect Date"</s>
|
<s>[INST]convert nvarchar to int
Hi, I have a table like the below
CREATE TABLE \[dbo\].\[myCodes\](
\[Code\] [nvarchar] NULL
) ON \[PRIMARY\]
GO
INSERT \[dbo\].\[myCodes\] (\[Code\]) VALUES (N'T0146')
INSERT \[dbo\].\[myCodes\] (\[Code\]) VALUES (N'T0108')
INSERT \[dbo\].\[myCodes\] (\[Code\]) VALUES (N'T0107')
INSERT \[dbo\].\[myCodes\] (\[Code\]) VALUES (N'T0106')
INSERT \[dbo\].\[myCodes\] (\[Code\]) VALUES (N'T0098')
INSERT \[dbo\].\[myCodes\] (\[Code\]) VALUES (N'-8843')
INSERT \[dbo\].\[myCodes\] (\[Code\]) VALUES (N'-8708')
INSERT \[dbo\].\[myCodes\] (\[Code\]) VALUES (N'6934')
INSERT \[dbo\].\[myCodes\] (\[Code\]) VALUES (N'-6933')
INSERT \[dbo\].\[myCodes\] (\[Code\]) VALUES (N'6697')
INSERT \[dbo\].\[myCodes\] (\[Code\]) VALUES (N'6584')
I wish to return only the the positive values from the column.
For example, -8843 would return 8843
T0098 would return only the numeric, thus 0098
etc, etc
Kindly assist,
Many thanks
[/INST]Does below query work?
select *, abs(replace(Code,'T','')) from mycodes</s>
|
<s>[INST]How to write query generate unique Id for concate both columns search parts and company id ?
I work on sql server 2012 . I face issue I can't generate unique Id from merge or concave both columns
Search Parts and Company ID and generated Id must be on column Generated ID
to be easier and fast on search
so Please How to generate unique Id from both column Search Parts and Company ID
and if both column repeated value both get same Id
so please How to do that
AS Example
SearchParts CompanyId GeneratedId
A5ghf7598f7GGHYUTYA 3456 901
when concate both columns Search Parts and Company Id generate Id
and take same Id in case of repeated
but main idea generate number unique for both column search parts and company id
every search parts text and CompanyId must be unique and take unique Id on generated Id
create table #partswithcompany
(
SearchParts nvarchar(200),
CompanyId int,
GeneratedId INT
)
insert into #partswithcompany (SearchParts,CompanyId,GeneratedId)
values
('A5ghf7598fdmlcpghjk',1234,NULL),
('AKLJGSA7598fdmlcpghjk',5870,NULL),
('A5ghfJKKJGHHGghjk',9081818,NULL),
('KHJLFFS8fdmlcpghjk',123345,NULL),
('A5ghf7598f7GGHYUTYA',3456,NULL),
('A5ghfJKKJGHHGghjk',9081818,NULL),
('A5ghf7598f7GGHYUTYA',3456,NULL),
('A5ghf7598f7GGHYUTYA',3456,NULL)
Expected Result
SearchParts CompanyId GeneratedId
A5ghf7598fdmlcpghjk 1234 5
AKLJGSA7598fdmlcpghjk 5870 9
A5ghfJKKJGHHGghjk 9081818 8
KHJLFFS8fdmlcpghjk 123345 6
A5ghf7598f7GGHYUTYA 3456 7
A5ghfJKKJGHHGghjk 9081818 8
A5ghf7598f7GGHYUTYA 3456 7
A5ghf7598f7GGHYUTYA 3456 7
[/INST],
Based on Viorel-1's answer, you could create a trigger or procedure to update the GeneratedId if newly created data is inserted tomorrow.
Please refer below example and check whether it is helpful:
--insert some new data
insert into #partswithcompany (SearchParts,CompanyId,GeneratedId)
values
('A5ghf7598fdmlcpghjk',1234,NULL),
('AKLJGSA75fukfgjpghjk',5870,NULL),
('A5ghfJKKJdfhgetrhsGghjk',818,NULL)
--update GeneratedId with same search parts and company id repeated
update a
set a.GeneratedId=b.GeneratedId
from #partswithcompany A
INNER JOIN #partswithcompany B ON A.SearchParts=B.SearchParts AND A.CompanyId = B.CompanyId
WHERE a.GeneratedId IS NULL and b.GeneratedId is not null
--update GeneratedId with different search parts and company id
; with M as
(
select a.*, dense_rank() over (order by a.SearchParts, a.CompanyId) as n
from #partswithcompany A
INNER JOIN #partswithcompany B ON A.SearchParts=B.SearchParts AND A.CompanyId = B.CompanyId
WHERE a.GeneratedId IS NULL and b.GeneratedId is null
)
update M
set GeneratedId = (select max(GeneratedId)+n from #partswithcompany where GeneratedId is not null)
select * from #partswithcompany
Output:
SearchParts CompanyId GeneratedId
A5ghf7598fdmlcpghjk 1234 2
AKLJGSA7598fdmlcpghjk 5870 4
A5ghfJKKJGHHGghjk 9081818 3
KHJLFFS8fdmlcpghjk 123345 5
A5ghf7598f7GGHYUTYA 3456 1
A5ghfJKKJGHHGghjk 9081818 3
A5ghf7598f7GGHYUTYA 3456 1
A5ghf7598f7GGHYUTYA 3456 1
A5ghf7598fdmlcpghjk 1234 2
AKLJGSA75fukfgjpghjk 5870 7
A5ghfJKKJdfhgetrhsGghjk 818 6</s>
|
<s>[INST]Columnstore Index and Analytical Queries
All,
We are looking at using the Data Virtualization layer in SQLServer 2019 BDC to run Analytical Queries against Operational/LOB Systems (Claims Management database, Accounting database).
Assuming that I create Non-Clustered Columnstore Index on top of Tables that contain Rowstore Clustered Index (and Non-Clustered Rowstore Index), how will the source system know what type of a query (Transactional/Analytical) has been submitted in order to use the relevant Index? is it left to the Query Optimizer alone to identify the query type?
What if the Analytical query fetches a range of rows instead of using aggregates, group by ... etc? Would it use the Rowstore Index or Columnstore Index?
The source database will be less impacted only if the Analytical query uses the Columnstore Index since this index structure also has the copy of the data for itself.
To summarize, how do I ensure that all the queries coming from Polybase (Data Virtualization layers) end up in using Non-Clustered Columnstore Index only?
Thanks,
grajee
[/INST]is it left to the Query Optimizer alone to identify the query type?
Yes.
> To summarize, how do I ensure that all the queries coming from Polybase (Data Virtualization layers) end up in using Non-Clustered Columnstore Index only?
That sounds like a big challenge to me.
Or have the Polycase guys to read from a readable secondary.</s>
|
<s>[INST]Intelli sense for linked server objects
Hi,
Will intelli sense work for linked server objects ? My searching indicates that its a no. Can someone confirm it ?
thanks[/INST]I don't use IIntellinonsense myself, but keep in mind that a linked server could be running Oracle or Postgreas, it could be an Excel file or a Hadooop cluster. It seems unlikely that SSMS would support all of that.
Yes, 90% of the linked servers in this world is another SQL Server instance, but I would not expect SSMS to handle this special case.
But why don't you test?</s>
|
<s>[INST]MSDN Forum: Msg 7346, Level 16, State 2, Line 1
PLS HELP
What mean this error:
OLE DB provider "SQLNCLI11" for linked server "servername" returned message "Row handle referred to a deleted row or a row marked for deletion.".
Msg 7346, Level 16, State 2, Line 1
Cannot get the data of the row from the OLE DB provider "SQLNCLI11" for linked server "servername".
[/INST],
Please share your SQL query and execute the query normally in SSMS such as running it locally at the remote server to check on them explicitly.
You error may be due to data inconsistency due to that distributed query was contradicted with another DML operation running on the same data entity concurrently.
Please refer below suggestions and check whether any of them is working:
- Make sure that all tables have primary keys and no duplicated records exists while doing insert, update and delete.
- Change the isolation level to a proper one since you may face this error if using snapshot isolation level.
- Add table locks if necessary.</s>
|
<s>[INST]How to Change datatype of all column to Unicode datatype for all base table in a database
Due to storing values from language specific diacritics (Spanish, French, German) I am trying to change the datatype of a column to Unicode datatype.
• Varchar to nvarchar
• char to nchar
So all column datatype to its respective Unicode datatype.
For all tables in a specific database.
I tried like this as below:-
ALTER TABLE dbo.Employee
ALTER COLUMN FirstName NVARCHAR(255) NOT NULL
but doing for 500 tables having 60 column means i have to write 3000 times alter statement
Can it be possible to do in a single statement?
Please help
Many Thanks
[/INST]Please refer below:
SELECT TABLE_CATALOG
,TABLE_SCHEMA
,TABLE_NAME
,COLUMN_NAME
,'ALTER TABLE ['+TABLE_SCHEMA+'].['+TABLE_NAME+'] ALTER COLUMN ['+COLUMN_NAME+'] '+
case when DATA_TYPE='Varchar' then 'NVARCHAR(255)' else 'NCHAR(255)' end
+ ' NOT NULL'as 'code'
FROM INFORMATION_SCHEMA.COLUMNS
where DATA_TYPE in ('Varchar','char')
Above generates an ALTER TABLE statement for each column of all tables in one database for you, then you could execute them all at once.</s>
|
<s>[INST]does cdc get affected by sql server restart
we have a couple of databases and tables that are enabled for cdc.
would restarting the sql server affect the cdc enabled databases or tables in any way.
please guide.
thanks
[/INST]What do you mean with "affected"? It would be quite a bad feature, if it would not survive server restarts. I don't do CDC myself, but I would be very disappointed if it did not just keep jogging along.</s>
|
<s>[INST]SQL Server Converting Date, Time to UNIX Epoch time (Pre-SQL 2016)
I am currently trying to convert SQL server (2008 R2 and 2012) audit logs from .sqlaudit file to csv/json/txt via PowerShell sqlcmd command. There is no issues doing this.
Something like this:
Invoke-sqlcmd -ServerInstance ...I -Query "SELECT * FROM sys.fn_get_audit_file ('\path\Audit-20210210-210446_F3B4AE48-04C4-4A14-AE30-F1AEB2AFF123_0_132580264066030000.sqlaudit',default,default);" | ConvertTo-Json -Depth 1 | out-file .....
However I need the date output in UNIX epoch time format (in milli sec).
I tried the datediff command however SELECT DATEDIFF(s,'1970-01-01',event_time) * 1000 does not work as this 13-digit value exceeds SQL integer limit.
I know form SQL 2016 there is big int, however older sql version does not have this.
Wondering what are the options?
I might try via PS on a different script - not sure how Win 2012 PS handled big int/conversion to big int.
Thanks
[/INST]If you believe that *bigint* is not always available, then try something like this:
select cast(datediff(s, '1970-01-01', event_time) as varchar(11)) + '000'</s>
|
<s>[INST]Can I have different versions of a stored procedure in DACPAC deploy based on the SQL Server version level due to syntax changes?
I have a few stored procedures that will require slightly different but critical syntax for option hints added to some version of SQL server but these would be unrecognized and error in early versions of SQL server prior to SQL Server 2014. Is there a way to write your procedure deploy scripts or other options in DACPAC to maintain and deploy different versions of the same scripts and have one version deploy on >SQL 2014 and a different version deploy on < SQL 2014?[/INST]You might try to check the version inside the stored procedure. If the target SQL server is 2014 and later you can use the critical syntax for option hints, otherwise you do not use them.
The other way you might try is to remove the stored procedure from the object list in the database project. Instead, you create two None Build scripts for different versions of SQL. In the Post Deployment script, you can call one of the files based on the SQL version.</s>
|
<s>[INST]Run DB restore and backup at same time?
Hello, say I have the following scenario:
1 - Perform a long running restore of a large DB (from a backup of another SQL Server as source) with brand new name (this DB doesn't yet exist on target SQL Server) i.e. starts at 9pm takes two hours to complete restore
2 - We have a scheduled nightly SQL Agent DB backup job starts at 10pm on this target server that the long restore is running so both restore and backup processes would overlap
Could this be potentially dangerous and cause DB corruption or any other things I should be concerned/aware of?
Thanks in advance.
[/INST]the operation as such cannot cause corruption. What could happen is that you overtax the I/O subsystem. But as long as the I/O subsystem is safe and sound it should not go clobbering any disks. However, you may have to accept that both operations are taking longer time than if they had not overlapped.</s>
|
<s>[INST]How to return results where (row by row) column 1 data must be different from column 2 in SQL server
Hi everyone
I need to work out how to return results on two columns where (row by row) column 1 must be different from column 2 and both columns also need to contain distinct values (in SQL server)
- the main essence of the question is how to ensure results are different from column 1 compared with column 2 on a row by row basis..
thank you!
[/INST]I interpret "distinct values" as having values not equal to NULL.
In that case, my suggestion would be:
SELECT * FROM table WHERE col1 != col2
(table, col1 and col2 needs to be replaced with whatever names you have for your table and columns)</s>
|
<s>[INST]Read-Only Replica between a Standard Edition and Enteprise Edition
We have 2 servers, one with standard edition and one enterprise edition of SQL Server.
We would like a couple of databases in the standard edition be replicated (for read-only purposes) into the 2nd server with the enterprise edition.
Given the current licenses, what's the best method to achieve that especially if we want it to be a real-time or near-real time replica?[/INST]Transactional replication or log shipping would be your options.
Log shipping is easier to set up, but users will have to be kicked out when a new log is applied.</s>
|
<s>[INST]Finding the difference between datetimes excluding sundays and Business holidays
Hi All,
Hope you are doing well!... I am trying to find the difference in the date times between the assign datetime and the completed datetime for a task completion (in hours and minutes) identified by the combination of ctextid and vbillid ..Sometimes a task involves multiple attempts and the number of times the combination of ctextid and vbillid appears is the totalholds.Also the business holiday dates in the holidays table should be excluded in the hours:minutes calculations plus the sundays should be excluded in hours:minutes calculations ( meaning sundays and business holidays should be excluded between and also inclusive of the assign and completed dates )
1\) If the assigned dates and the completed dates fall on US Business holidays or on Sundays those hours are not taken into account for total hours
2) If the assign date starts with a sunday or business holiday those hours are not taken into account and also if the completed date falls on a sunday or business holiday those hours are not taken into account.
3) Also if the times between the assigned dates and the completed date fall on Sundays or Business holidays then those hours are not taken into account
4) Also if the assigned and the completed fall on the same day and it is a Sunday or Business holiday those hours are considered zero for that hold
Please find the tables below:Can you please help me here
Input table
create table ##input
(ctextid int,
vbillid int,
assigndate datetime2,
completed datetime2
)
insert into ##input values
('23','11','1/25/2021 6:51','2/9/2021 16:55'),
('23','11','2/10/2021 6:51','2/12/2021 6:51'),
('34','16','1/7/2021 18:58','2/24/2021 9:00'),
('44','102','1/22/2021 9:56','2/9/2021 16:54),
('44','91','1/19/2021 16:35','1/20/2021 4:14'),
('75','57','1/19/2021 10:11','1/19/2021 13:16')
Holidays table
create table ##holidays
(description varchar (500),
holidaydate date
)
insert into ##holidays values
('New Year's Day','1/1/2021'),
('Martin Luther King's Birthday','1/18/2021'),
('President's Day','2/15/2021'),
('Memorial Day','5/31/2021'),
('Independence Day','7/5/2021'),
('Labor Day','9/6/2021'),
('Columbus Day','10/11/2021'),
('Veterans Day','11/11/2021'),
('Thanksgiving Day','11/25/2021'),
('Christmas Day','12/24/2021'),
('New Year's Day','12/31/2021')
Output table
create table ##output
(ctextid int,
vbillid int,
hoursintotal float,
totalholds int
)
insert into ##output values
('23','11','370.04','2'),
('34','16','926.02','1'),
('44','102','366.57','1'),
('44','91','11.38','1'),
('75','57','3.04','1')
Thanks,
Arun
[/INST]Please refer below:
Step One: create one function named [fn_GetTotalWorkingHours] to calculate the working hours exclude Sunday.
CREATE FUNCTION [dbo].[fn_GetTotalWorkingHours]
(
@DateFrom Datetime,
@DateTo Datetime
)
RETURNS DECIMAL(18,2)
AS
BEGIN
DECLARE @TotalWorkDays INT, @TotalTimeDiff DECIMAL(18, 2)
SET @TotalWorkDays = DATEDIFF(DAY, @DateFrom, @DateTo)
-(DATEDIFF(WEEK, @DateFrom, @DateTo) * 1)
-CASE
WHEN DATENAME(WEEKDAY, @DateFrom) = 'Sunday'
THEN 1
ELSE 0
END+CASE
WHEN DATENAME(WEEKDAY, @DateTo) = 'Sunday'
THEN 1
ELSE 0
END;
SET @TotalTimeDiff =
(
SELECT DATEDIFF(MINUTE,
(
SELECT CONVERT(TIME, @DateFrom)
),
(
SELECT CONVERT(TIME, @DateTo)
)) / 60.0
);
RETURN (SELECT(@TotalWorkDays * 24.00) + @TotalTimeDiff)
END
GO
Step Two: Call this function in below query:
;WITH cte1 as (
SELECT a.ctextid,a.vbillid
,case when CONVERT(date, DATEADD(DAY,number,a.assigndate))=CONVERT(date, a.completed)
then CONVERT(date, a.completed) else DATEADD(DAY,number,CONVERT(date, a.assigndate)) end [ALLDate]
FROM master..spt_values,##INPUT a
WHERE type = 'P'
AND DATEADD(DAY,number,CONVERT(date, a.assigndate)) <= CONVERT(date, a.completed))
,cte2 as
(select a.*
,case when DATENAME(DW,[ALLDate])='Sunday' then 1 else 0 end IsSunday
,IIF(b.holidaydate is not null,1,0) IsHoliday
from cte1 a
left join ##holidays b
on ALLDate=CONVERT(date, b.holidaydate ))
,CTE3 AS
(select ctextid,vbillid,SUM(IsHoliday) SUMHOLIADY
from cte2
WHERE IsHoliday=1 AND IsSunday=0
GROUP BY ctextid,vbillid)
,CTE4 AS
(select DISTINCT A.ctextid,A.vbillid
,[dbo].[fn_GetTotalWorkingHours] (assigndate,completed) hours
from ##input A)
,CTE5 AS (
select A.ctextid,A.vbillid,sum(hours) sum, count(hours) count
from CTE4 A
group by A.ctextid,A.vbillid)
SELECT A.ctextid,A.vbillid
,A.SUM-(ISNULL(B.SUMHOLIADY,0)*24) hoursintotal ,COUNT totalholds
FROM CTE5 A
LEFT JOIN CTE3 B
ON A.ctextid=B.ctextid AND A.vbillid=B.vbillid
Output:
ctextid vbillid hoursintotal totalholds
23 11 370.07 2
34 16 926.03 1
75 57 3.08 1
44 91 11.65 1
44 102 366.97 1
After checking, the hoursintotal from my output is a little different from your's.
I checked manually with one row ('75','57','1/19/2021 10:11','1/19/2021 13:16') and calculated the hours manually. The minutes between the two dates was 185 and the hoursintotal could be 185/60.00=3.08 which was not 3.04 you provided.
Please check above and provide more sample data and expected output if you have any concern or my query is not working.</s>
|
<s>[INST]SQL Server Express 10GB Limit - Total DB size or Used DB size?
SQL Server Express 10GB Limit - Total DB size or Used DB size?
Couldn't find a straight answer anywhere and it it quite important for my monitoring purposes.
How does the 10GB limit apply with SQL Express?
I.E. as soon as the DB grows to 10GB does it stop taking transactions?
OR
DB can grow to 10GB+ but as soon as used space hits 10GB it stops?
OR
DB is 10GB max but only stops when used space also hits 10GB?[/INST]The total space used by that data file should be 10GB no matter free or used. If suppose you have a data file with 5 GB data and 5 GB free space and you run alter database command to increase size it will flash error as size is going more than 10
> I.E. as soon as the DB grows to 10GB does it stop taking transactions?
Yes it will if transaction is adding data, not if transaction is reading. Log file has no restriction of 10 GB
> DB can grow to 10GB+ but as soon as used space hits 10GB it stops?
No, the total size will be considered. Your transaction will continue to insert data till data file is reached 10 GB. The error will be flashed if you try to run alter database command to increase file size more than 10 GB.
> DB is 10GB max but only stops when used space also hits 10GB?
You need to understand that DB will grow till 10GB limit is used post that it will stop.</s>
|
<s>[INST]Case When ISNULL
Hi,
I have the following Case statement, but my logic doesn't seem to work, any idea why this is please?
case when method = 'TP' and second_method ISNULL then 'New' end as Method_Type
This is my error message:
An expression of non-boolean type specified in a context where a condition is expected, near 'ISNULL'.
[/INST]Provide a space in between "IS NULL"
try:
case when method = 'TP' and second_method IS NULL then 'New' end as Method_Type</s>
|
<s>[INST]DateDiff Error
Hi,
I have a DATEDIFF query but upon executing my code, I get an error message that I am unsure how to resolve, any ideas please?
Arithmetic overflow error converting expression to data type datetime.**strong text**
DATEDIFF(month, Comp_Date, Down_Date) AS Months_to_end
Date variables are formatted as YYYYMMDD[/INST]Check an approach:
datediff(month, cast(Comp_Date as varchar(max)), cast(Down_Date as varchar(max)))</s>
|
<s>[INST]Strange Login and AppDomain xx created
On a sql 2k16, when I go through error logs, I find a lot of messages las follows
Server Date Process Count Text
SQL2K12 2021-03-15 13:30:44.640 spid17s 1 AppDomain 39 (MDS.mds_schema_user[runtime].38) unloaded.
SQL2K12 2021-03-15 13:00:15.550 spid62 1 AppDomain 40 (master.sys[runtime].39) created.
SQL2K12 2021-03-15 13:00:15.550 spid62 1 AppDomain 40 (master.sys[runtime].39) created.
SQL2K12 2021-03-15 10:00:43.090 spid45s 1 AppDomain 39 (MDS.mds_schema_user[runtime].38) created.
Not sure what this appDomain creating and unloading?
Thanks[/INST]That is completely normal and expected when you are running MDS.</s>
|
<s>[INST]can i use over clause after having on sql server 2012 ?
can i use over clause after having on sql server 2012 ?
I have technical question
can i use over clause over count on having clause
as example
select partid,product
from product
having count(partid) over
are this valid please answer me
what i know is over can use before from
but are this possible after having
having over partition or
having over order by
[/INST]Windowed functions can only appear in the SELECT or ORDER BY clauses.The example mentioned in your question is invalid and will return an error:
select partid,product
from product
having count(partid) over
Having is to specify filter conditions for the group or or an aggregate returned in the previous step.</s>
|
<s>[INST]GMSA, MSA for SQL Server
Need to find out if I can configure managed service account to run SQL server and agent services?
I know GMSA is not available for 2008 r2 with SQL 2008 R2, is MSA an option?
How about Windows 2012 and SQL 2012 (and R2 versions as well)
Thanks
[/INST]\> I know GMSA is not available for 2008 r2 with SQL 2008 R2, is MSA an option?
No, SQL 2008 R2 not supported for MSA. SQL Server 2012 or higher is required to support the use of MSAs. And Windows Server 2008 R2 or higher is required to supported the use of MSA..
Microsoft SQL Server 2014 is the first version to supports GMSAs. To use a GMSA for SQL Server 2014 or later, the operating system must be Windows Server 2012 R2 or later. Servers with Windows Server 2012 R2 require KB 2998082 applied so that the services can log in without disruption immediately after a password change.
> \> How about Windows 2012 and SQL 2012 (and R2 versions as well)
Windows 2012 and SQL 2012 are supported to use MSA.</s>
|
<s>[INST]SQL Server 2008R2 Security Update 10.50.6560.0
Does SQL Server 2008R2 Security Update 10.50.6560.0 (Meltdown/Spectre) include the TLS1.2 update 10.50.6542.0?
I can see the TLS1.2 update is a lower build number, but I can't find anywhere that states that the higher update includes the lower one(s) - there's 3 others post SP3 too - as it's not listed as a rollup patch.
[/INST]All updates are cumulative. A higher version number means all previous patches are included. 6560 is greater than 6542.
So to answer your question, YES.</s>
|
<s>[INST]Inner Join using SQL SMS
Hi. Noob here trying to figure out SQL SMS queries. I'm trying to take a query that works in MS Access and use it in SQL Server Management Studio. I start getting syntax errors at the "inner join". If I just run the first select-from-where statement all is good, but after I add the inner join, nothing works. I get a 'syntax error' at the inner join line, and then nothing works after that.
I don't think I'm far off, but i can't seem to figure out what the issue is. Can anyone help me figure this out??
select all_wr_table.INSP_DATE
from works.INSPECTIONS_VALVE_INSPECTION as all_wr_table
where(
((all_wr_table.DATEWORK is null) and (all_wr_table.VALVE_INOPERABLE = 'True')) or
((all_wr_table.DATEWORK is null) and (all_wr_table.VALVE_LEAKING = 'True')) or
((all_wr_table.DATEWORK is null) and (all_wr_table.VALVE_SPINS = 'True')) or
((all_wr_table.DATEWORK is null) and (all_wr_table.VALVE_OTHER = 'True')) or
((all_wr_table.DATEWORK is null) and (all_wr_table.VALVEBOX_STRAIGHT = 'True')) or
((all_wr_table.DATEWORK is null) and (all_wr_table.VALVEBOX_BROKEN = 'True')) or
((all_wr_table.DATEWORK is null) and (all_wr_table.VALVEBOX_ADJUST = 'True')) or
((all_wr_table.DATEWORK is null) and (all_wr_table.VALVEBOX_OTHER = 'True')) or
((all_wr_table.DATEWORK is null) and (all_wr_table.VALVECHAMBER_REPAIRS_TO_CONCRE = 'True')) or
((all_wr_table.DATEWORK is null) and (all_wr_table.VALVECHAMBER_REPAIRS_TO_BRICK = 'True')) or
((all_wr_table.DATEWORK is null) and (all_wr_table.VALVECHAMBER_PUMPOUT = 'True')) or
((all_wr_table.DATEWORK is null) and (all_wr_table.VALVECHAMBER_OTHER = 'True')) or
((all_wr_table.DATEWORK is null) and (all_wr_table.VALVEBOX_FULL_OF_DEBRIS = 'True'))
)
inner join
(select max(most_recent_Table.INSP_DATE) as MaxOfINSP_DATE, most_recent_Table.FACILITYID
from works.INSPECTIONS_VALVE_INSPECTION as most_recent_Table
group by most_recent_Table.FACILITYID
order by most_recent_Table.FACILITYID)
on
(all_wr_Table.FACILITYID=most_recent_Table.FACILITYID) and (all_wr_Table.INSP_DATE = most_recent_Table.MaxOfINSP_DATE)[/INST]You need to put INNER JOIN between FROM and WHERE. And also you cannot use ORDER BY in the subquery. Try this:
select all_wr_table.INSP_DATE
from works.INSPECTIONS_VALVE_INSPECTION as all_wr_table
inner join
(
select max(most_recent_Table.INSP_DATE) as MaxOfINSP_DATE, most_recent_Table.FACILITYID
from works.INSPECTIONS_VALVE_INSPECTION as most_recent_Table
group by most_recent_Table.FACILITYID
as most_recent_Table
on
(all_wr_Table.FACILITYID=most_recent_Table.FACILITYID) and (all_wr_Table.INSP_DATE = most_recent_Table.MaxOfINSP_DATE)
where(
((all_wr_table.DATEWORK is null) and (all_wr_table.VALVE_INOPERABLE = 'True')) or
((all_wr_table.DATEWORK is null) and (all_wr_table.VALVE_LEAKING = 'True')) or
((all_wr_table.DATEWORK is null) and (all_wr_table.VALVE_SPINS = 'True')) or
((all_wr_table.DATEWORK is null) and (all_wr_table.VALVE_OTHER = 'True')) or
((all_wr_table.DATEWORK is null) and (all_wr_table.VALVEBOX_STRAIGHT = 'True')) or
((all_wr_table.DATEWORK is null) and (all_wr_table.VALVEBOX_BROKEN = 'True')) or
((all_wr_table.DATEWORK is null) and (all_wr_table.VALVEBOX_ADJUST = 'True')) or
((all_wr_table.DATEWORK is null) and (all_wr_table.VALVEBOX_OTHER = 'True')) or
((all_wr_table.DATEWORK is null) and (all_wr_table.VALVECHAMBER_REPAIRS_TO_CONCRE = 'True')) or
((all_wr_table.DATEWORK is null) and (all_wr_table.VALVECHAMBER_REPAIRS_TO_BRICK = 'True')) or
((all_wr_table.DATEWORK is null) and (all_wr_table.VALVECHAMBER_PUMPOUT = 'True')) or
((all_wr_table.DATEWORK is null) and (all_wr_table.VALVECHAMBER_OTHER = 'True')) or
((all_wr_table.DATEWORK is null) and (all_wr_table.VALVEBOX_FULL_OF_DEBRIS = 'True'))</s>
|
<s>[INST]MSSQL Audit Log
I renamed sa account and disabled. Why my audit log showing sa activities?
EventTime server_principal_name session_server_principal_name statement
14-11-20 0:56 sa
What is this entry for sa account because I don't have sa account[/INST]Please execute the following query to check if the sa account you see is the real original sa account:
SELECT name
FROM sys.sql_logins
WHERE sid = 0x01;
The sa account always has 0x01
Ensure no other logins are named sa
SELECT sid, name
FROM sys.sql_logins
WHERE name = 'sa';
Next check in the audit log what this sa account is doing (maybe simply an attempt to connect by someone and it failed ?)</s>
|
<s>[INST]Kill DB backup process?
Hello, will sending a KILL/terminate command potentially corrupt/negative impacts during a long running large DB BACKUP ?
Thanks in advance.[/INST]Are you trying to kill the process of backup? If yes, you can kill it, the operation will not impact Databases, but you have to be cautious as if you kill backup process, it has to ROLLBACK which will take some or more time.</s>
|
<s>[INST]Cast a varchar field with mixed time format to time (0)
Hi
I have a [time] field- varchar datatype and it has got values in mixed formats as below
14:24:00
07:00.0
10:00:56.7730000
54:80.0 (exclude wrong format)
I am trying to cast the field as time (0) but it is causing conversion error.
Can some one please help me with sort this out?
Thanks[/INST]Try identifying the possible formats and interpretations. For example, for shown data, try something like this:
select *,
try_cast(case when MyColumn like '[0-9][0-9]:[0-9][0-9].[0-9]%' then '00:' + MyColumn else MyColumn end as time(0)) as [Time]
from MyTable
Show details if there are more cases.</s>
|
<s>[INST]Adding or Deleting a Login Fails with xp_cmdshell Error
I have such a weird issue. I have a brand new SQL2019 FCI with CU9 and I can't add or delete logins without having xp_cmdshell enabled. If it isn't I get this error when trying to delete/add/disable etc a login:-
SQL Server blocked access to procedure 'sys.xp_cmdshell' of component 'xp_cmdshell' because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of 'xp_cmdshell' by using sp_configure. For more information about enabling 'xp_cmdshell', search for 'xp_cmdshell' in SQL Server Books Online.
Why does login admin activity need xp_cmdshell enabled? [/INST]What you describe is almost certainly due to someone creating a DDL trigger which requires xp_cmdshell.</s>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.