Dataset Viewer
Auto-converted to Parquet
text
stringlengths
209
10.7k
<s>[INST]@@SERVERNAME when using sqlpackage.exe in multi instance environment We are using sqlpackage.exe to deploy a database. In the deploy process, we have a script that creates a loopback linked server: EXEC master.dbo.sp_addlinkedserver @server = N'loopback' ,@srvproduct=N'' ,@provider=N'SQLNCLI' ,@datasrc=@@SERVERNAME -- This is the important part! The problem we face is that in the deploy process the `@@SERVERNAME` evaluates to the default instance, not the target server specified, which is a named instance. I assume the source of the problem is that the deploy happens "in the name of" the default instance...? I tried to find a solution for this problem, e.g specifying a parameter for sqlpackage.exe that would resolve this "issue", but so far no luck. Our quick solution was to first execute the specific script in the target server using SSMS, creating the loopback with the right server, and then deploy, but obviously we are interested in a more "resistant" solution. I would assume there should be a solution so `@@SERNERNAME` evaluates to the TargetServerName I specify for the tool. [/INST]The only way I have found that you can create a linked server using @@SERVERNAME in the script is to delete the definition of the Linked Server as an object and then put that script in a PreDeployment script and it will pick up the ServerName with the instance and create the linked server. I just tested it and it works like you expect it to. Sorry for the delay.</s>
<s>[INST]sqlcmd options on print / display Hello i need some help with sqlcmd utility at linux I have this select statement, but it display both at start with the ----- 1> select 'grant select on ' + name + ' to READONLY' + CHAR(10) + 'go' from sysobjects where type = 'U' or type = 'V' or type = 'P' 2> go ------------------------------------------------------------------------------------------------------------------------------------ then a the end show the numbers (34 rows affected) how can the --- and the ( x rows affected) be ignored? is there away in the sqlcmd to pass some parameter to ignore the lines? thank you [/INST]Use SET NOCOUNT ON in the SQL to suppress the rowcount. To suppress the header, use the option `-h-1`, for instance: sqlcmd -h-1 -Q"SET NOCOUNT ON SELECT @@version"</s>
<s>[INST]TRUNCATE table permissions, Large number of tables So as a DBA I have inherited a app where lots of TRUNCATE TABLE statements are being used in the stored procedures, I could find around 40 different tables being mentioned on TRUNCATE statement in one database itself on various sp's. Currently I have given ALTER TABLE permissions on those tables, but i am trying to remove that permission. Replacing TRUNCATE by DELETE could be one of the options, but given the large number of sps that use truncate, I think there could be some slowness there. Plus there is a reluctance to make a code change on so many sp's from app, but I am looking into it. Next, I have looked into the EXECUTE AS option, the testing that I have done - I don't think the EXECUTE AS OWNER can be used in between the sp code - Looks like it has to be mentioned at the top , which I don't want to do as I was trying to just use the EXECUTE AS only on the TRUNCATE module statements - The TRUNCATE statements are scattered all over the sp. **This works -** ALTER PROCEDURE \[dbo\].\[truncate_test\] WITH EXECUTE AS OWNER AS BEGIN **This does not:** ALTER PROCEDURE \[dbo\].\[truncate_test\] AS BEGIN EXECUTE AS OWNER TRUNCATE TABLE TABLE_1 REVERT END So I am trying to avoid running all those many sp's under owner. I also don't want to create like 40 sp's which are for per table truncate and give exec on them to app and have them change the code which includes that sp instead of truncate statement. Whats the solution to this, has anyone seen / been thru this before? Is there a sp that I can create which takes the table name as parameter and I can then have the app make the code change in their many sp's and replace the truncate by that sp where they just need to give in the table name, I think I have seen that mentioned on one of the forums but wanted to see if there are no other security side-effects of it and this post is basically to know how DBA's are solving this issue? Thanks a lot. [/INST]'t use sysobjects to look up meta-data, not the least if you work with schemas. This is an old compatibility view for SQL 2000, where schemas worked differently. The look up on the table name only works if you only have tables in the dbo schema. If you want to handle multiple schemas work with the object id instead. You can retrieve it with the object_id() function.</s>
<s>[INST]SQL Server 2016 Licensing - Restore Only server I have a server that is going to be used for testing the restore of backup from across the environment. It will not be running DBCC CheckDB or anything else once a restore is done, just delete the database and move on to the next restore test. Will I be able to use a developer license or will I need to get an enterprise license?[/INST]From SQL Server 2016 guide which is present online also. I quote > A production environment is defined as an environment that is accessed by end-users of an application (such as an Internet website) and that is used for more than gathering feedback or acceptance testing of that application. Since you are just restoring the database and then deleting it I do not feel this to be issue. But again authoritative statement should come from MS Licensing expert.</s>
<s>[INST]Extended Events - Capture connection string used to connect to SQL Fellow SQLers, I am trying to see if I can capture the actual connection string used when a user connects to SQL. I know I can capture their options (Set ….. etc) but cannot find an event that give me the actual connection string. Is it doable with Ext Events? Thx MG [/INST]That data does not exist in SQL Server. The connection string is how the caller connects to SQL Server. What exactly are you looking for?</s>
<s>[INST]Backup without "Copy Only" Hi, I wonder if a manual backup of an SQL server database without "Copy Only" mode will interrupt a scheduled backup plan set up for the database? If so, is there a way to fix it? Thanks in advance![/INST]It will not affect the backup schedule. Well, in one situation maybe: you start the backup just before the scheduled time, so that your backup runs when the backup jobs starts. I don't know what happens here. But in that case, COPY_ONLY or not does not matter. However, failing to use COPY_ONLY could still damage the backup scheme, if it includes differential backups, the next differential backup will be based on your manual backup. This can cause some panic if you get a disaster and you are not able to restore the database from the schedule backups.</s>
<s>[INST]SQL Always On Availability Group Deployment Hi there, I would like to setup a SQL AlwaysOn Availability Group on 2 new SQL servers. For the storage part, as I know SQL AG doesn't require shared storage for the database replication. However, if I want to use LUN on my servers to expand the storage, can SQL AG still be configured with shared storage? Like example below: There will be 2 LUNs Server A attached to LUN A Server B attached to LUN B Will above storage settings work for SQL AlwaysOn Availability Group configuration as they are not sharing the same LUN. Thanks.[/INST]Yes they will work without any issue. Like you said plain SQL AG does not needs shared storage so the working of both the storage would be mutually exclusive and hence you can have different LUN's</s>
<s>[INST]Encrypt stored proceudres with password. Hi All, Is there a way to encrypt stored procedure code with password ?. I am not talking about the keyword "WITH ENCRYPTION" in the stored procedure when creating it but actually applying a password to it so that I can also decrypt it with that password. Don't want to create a master key and certificate for it either. Is there a way ? This is for any SQL Server versions from 2012 to 2019. Thanks.[/INST]No. Think of it. To be able to run the stored procedure, SQL Server needs to be able read the SQL code. So if there were such a feature, user would only be able to run the procedure if the user has the password.</s>
<s>[INST]sql query help needed Hi All, Thank you for helping those who are in need. I need a help in writing a sql query to get the desired out put shown below, I have multiple records with same id in a table other columns may vary, we need to process those grouped records and get a single record pick them as shown below. some columns have nulls ignore them if the value exists in other record, pick that value, if no value exists in any of the rows in that group just leave as null create table #Tempaddress (id int, name varchar(10), Addr1 varchar(50), Addr2 varchar(50), state char(2), zip char(5)) insert into #tempaddress Values( 1 ,'Tom', null, 'xyz', 'OH',NULL) ,(1, 'Tom', 'zxy', 'xyz', NULL,NULL) ,(1, 'Tom', NULL, NULL, NULL,'28764') ,( 2 ,'Bill', null, 'xyz', 'AZ',NULL) ,(2, 'Bill', 'zxy', 'xyz', NULL,NULL) ,(3, 'Kate', 'zxy', 'xyz', NULL,NULL) Desired output 1 Tom zxy, xyz, OH,28764 2 Bill zxy, xyz, AZ, NULL 3 Kate, zxy, xyz, NULL,NULL[/INST]Also check a method that experiments with pivoting, for up to six values: ; with Q1 as ( select id, name, cast(Addr1 as varchar(max)) as v1, cast(Addr2 as varchar(max)) as v2, cast(state as varchar(max)) as v3, cast(Zip as varchar(max)) as v4 from #Tempaddress ), Q2 as ( select id, name, min(t) as t, val from Q1 unpivot ( val for t in ( v1, v2, v3, v4 ) ) as u group by id, name, val ), Q3 as ( select id, name, val, row_number() over (partition by id, name order by t) as rn from Q2 ) select id, name, [1], [2], [3], [4], [5], [6] from Q3 pivot ( max(val) for rn in ( [1], [2], [3], [4], [5], [6] ) ) as p order by id Dou you want to make a comma-separated text?</s>
<s>[INST]Can 32 bit connect into SQL Server 64 bit? Can a user connect using 32 bit SQL ODBC driver into SQL Server 64 bit version or do they need to use a 64 bit SQL ODBC driver? Thanks in advance.[/INST]They both can connect to either 32 or 64 bit databases. Use the 32 bit driver when the client application or process is 32 bit.</s>
<s>[INST]How to port my Express database to SQL Server in preparation for making website live I am creating a website in Visual Studio with C# (WebForms). It is a data-driven website, allowing the user to filter data, but not update it (read-only). The data tables, from my perspective, anyway, are huge - well over a million records in some of the tables. These are in a SQL Server Express database. I assume I will need to port that to "regular" SQL Server when I have the site hosted and "go live." Are there are any Tutorials on how to do that (port from Express to standard SQL Server)?[/INST]SQL Server Express Edition is licensed and suitable for production workloads. It's just has restrictions on the amount of resources it can use and the database size. So depending on how you host your web site and what the load on it is, you might not require a migration.</s>
<s>[INST]Problem with UPDATE over Linked server using Microsoft OLE DB Provider for ODBC drivers for MS Access Hi, I'm currently using SQL SERVER 2019 with ODBC driver for MS Access (installed via AccessDatabaseEngine2010 64bit) for linked server. On 3 different machines where SQL SERVER 2019 Express is installed (Windows 10) select function works: SELECT * FROM OPENQUERY(MYODBC,'SELECT qty from stock') and UPDATE UPDATE OPENQUERY(MYODBC,'SELECT qty FROM stock') SET qty = 2 but on the one machine (Windows Server 2016) SELECT works but UPDATE gives us the error: OLE DB provider "MSDASQL" for linked server "ildodbc" returned message "[Microsoft][ODBC Microsoft Access Driver] Cannot update. Database or object is read-only.". Msg 7343, Level 16, State 2, Line 183 The OLE DB provider "MSDASQL" for linked server "ildodbc" could not INSERT INTO table "[MSDASQL]". It's the same database and on all 4 machins we are logged with sa account to SQL Server, on windows with admin account. Any idea what can be the cause for this. Thanks[/INST]We tried with ACE OLE DB and it was the same thing, on our machines it worked, on theirs not, tbh it worked if we were logged locally in SSMS on the server, but the soon as we tried to call a stored procedure from another PC on the network, the procedure returned permission denied. This sounds like a double-hop problem. Then again, E:\\LegacyDB certainly sounds like a local disk, so I cannot really see how would happen here. Also, double-hop problem appears when you use Windows authentication. SQL Server then tries to impersonate the actual Windows user, but this does not work if the login was by NTLM and not Kerberos, or Kerberos is not set up properly.</s>
<s>[INST]Last 3 full months vs last year same 3 months dates Hi Guys I am looking for a way to use my date in SQL Server to show me the "last 3 full months vs last year same 3 months dates" not adding the current month - this is something that I want to hard code (Store Proc) and use in SSRS in a Date parameter. Or if I can specify X number of Months would be awesome like (last 2 months, last 3 months, last 12 Months). so for instance we are in the Month of October 2020 - when I run the SQL I want the dates to show: July 2020 August 2020 September 2020 July 2019 August 2019 September 2019 Thanks for all the feedback I really learn a lot from you guys.[/INST]SELECT GetDate() SELECT dateadd(m, -3, GetDate()), dateadd(m, -2, GetDate()), dateadd(m, -1, GetDate()) SELECT DATENAME(month, dateadd(m, -3, GetDate())) + ' ' + DATENAME(year, dateadd(m, -3, GetDate()))</s>
<s>[INST]Casting BIGINT as Varchar Err I have a SP like below for the, if I want to pass multiple ids like 1111, 2222 I am getting error even If I cast ID as varchar(100) BEGIN Declare @ID BIGINT SELECT @ID = 1111 SELECT * INTO TAB1 FROM TAB2 WHERE ID IN @ID .. .. SELECT * INTO TABn FROM TABm WHERE ID IN @ID END I tried below it didn't worked. with the above code I am forced to use only one value e.g. 1111 BEGIN Declare @ID VARCHAR(100) SELECT @ID = ('1111','2222') SELECT * INTO TAB1 FROM TAB2 WHERE CAST(ID as VARCHAR(100)) IN @ID .. .. SELECT * INTO TABn FROM TABm WHERE CAST(ID as VARCHAR(100)) IN @ID END [/INST]SELECT @ID = ('1111','2222') is not correct. Try the following script if your SQL server is 2016, 2017 or 2019: DECLARE @ID VARCHAR(100) SET @ID = '1111,2222'; SELECT value FROM STRING_SPLIT(@ID, ','); For you case: SELECT * INTO TAB1 FROM TAB2 WHERE ID IN (SELECT value FROM STRING_SPLIT(@ID, ','))</s>
<s>[INST]SQL Server Database log file max size setting problem Hi, Database was created with initial log file size 50 MB and max size set to 2 GB. While restoring database from pre production environment to test environment, it failed due to transaction log file full due to "ACTIVE_TRANSACTION". I increased max size to 100 GB. But After restore database, the max size is set to 2 GB again automatically. Can you please help out how this max size changes automatically. Please advise if any settings modifies this max size of log file after restore happens. Thanks Bala[/INST]On a restore of a database, the max size will always be what it was in the backup. You can have the restore command and the alter database modify file command right after so that transactions do not fill the transaction logs. -- First do the restore RESTORE DATABASE databasename FROM DISK='filename'; GO USE master; GO ALTER DATABASE databasename MODIFY FILE (NAME = internal_log_name_from_db,</s>
<s>[INST]Rebuild index in SQL server system database Hi, I just want to confirm , is it recommended to rebuild indexes in system database e.g. MSDB or distribution db in transactional replication. Thanks[/INST]There is no need to rebuild index of system databases definitely not for master and model database. There may be few conditions where you can rebuild index for msdb but that is rare as well. Tempdb being temporary one has no such requirement at all.</s>
<s>[INST]Query for a Stored Procedure SSMS: 18.6 SQL Server: 2014 I am writing a query and I need to have the following in my stored procedure. How do I write it in the query? Any help would be appreciated. Thank you. ========================================================= Parameter that allows a user to select that the revenue amount is over x amount (x= keyed in amount) ==========================================================[/INST]CREATE PROCEDURE dbo.uspGetCustomers @Amount money AS SELECT * FROM dbo.Sales WHERE SalesAmount > @Amount</s>
<s>[INST]Polybase DMVs erroring out All, I have a **SQLServer 2019** installation on Windows 10 Pro (Desktop at home) and I have enabled **Polybase** on it. However, I get the below error whenever I run any of the Polybase DMVs. **\*select \* from sys.dm_exec_compute_nodes select \* from sys.dm_exec_dms_services\*** Msg 782, Level 16, State 1, Line 2 **SQL Server Network Interfaces: No credentials are available in the security package** The version of SQLServer 2019 is : "Microsoft SQL Server 2019 (RTM-CU6) (KB4563110)" grajee [/INST]I can't say that I have that much more success. When I'm logged in with Windows authentication, I get "Login failed. The login is from an untrusted domain and cannot be used with Integrated authentication." I believe is due to that I am in a workgroup. If I log in as sa, I can run select * from sys.dm_exec_compute_nodes However, if I try: select * from sys.dm_exec_dms_services I get "Cannot execute the query "Remote Query" against OLE DB provider "MSOLEDBSQL" for linked server "(null)". Error processing metadata query sp_execute_memo: Object reference not set to an instance of an object." On the first attempt the query ran for five minutes before dying. I also find a dump in the log directory for Polybase. (On subsequent executions the error message is instant.) I also find that if I try to stop the Polybase services, the Data Movement service stops, but the Polybase engine service does not. If I kill it through Process Explorer and restart the service, the query again runs for five minutes before producing the same error message. For the record, I'm on CU7. (But you should not be on this CU, since Microsoft has pulled it due to an issue with database snapshots.)</s>
<s>[INST]Alter table switch partition to another filegroup of another table Is it possible to use "Alter table switch partition......." to move the partition to another other table which in different filegroup from the source table ?[/INST]You cannot directly switch a partition from the partitioned table to a table in a different file group, but you can do it indirectly. 1. Create a table (named SourceTemp) with the same structure as the partitioned table on the same filegroup 2. Switch the partition from the partitioned table to the table SourceTemp on the same filegroup 3. Export data from the table SourceTemp to the destination table on another file group. 4. Drop the table SourceTemp</s>
<s>[INST]Clarifying version of SQL Server Management Studio and inability to use certain functions Hello When I open Management Studio it tells me I'm in version 18.7.1 However when I tried to use the STRING_AGG function earlier in a query I got this error message: *'STRING_AGG' is not a recognized built-in function name.* I assumed that as I appeared to have MS 2018 functions like this would work. However I then clicked on 'help' and 'about' and it says, under SQL Server Management Studio that I'm on: 15.0.18358.0 Please can you advise what upgrade I should be asking IT to move me onto in order to let me to actually use 2018? Either that or am I doing something silly and obviously wrong and should be able to use the function (I used the correct syntax). Thanks [/INST]I think that the availability of functions is determined by the version of SQL Server, not by Management Studio only. Try executing *SELECT @@VERSION* to check the version of SQL Server. Which value did you get?</s>
<s>[INST]move sql server install to a new PC Hi, I have bought a new PC and am wondering how to transfer over the install of Visual Studio, SQL Server 2014 and SQL Server Management Studio from my old one. All the searches I do just seem to give me ideas on moving a database, not the install itself. Thanks, Col[/INST]If you're on a PC I would go the easy way: install VS and SQL Server on your new system and then just copy the mds and ldf files from your databases to your new system. Or backup/restore of the database(s). But this won't move any users, e.g. sql logins or sql agent jobs, because those information are in the system dbs of SQL Server. Moving the whole installation is a complete different thing. SQL Server is a service on your system. So you need to take care of registering all necessary dlls, create the service from scratch and so on. Also, you have to take care about folder / file permission and so on... That's not a clean way. Install SQL Srv 2014 from your installation media.</s>
<s>[INST]Delete records older than 12 months but the date is in YYYYMM format Hi, I have a table that gets updated with fresh data every month I am trying to delete records which are older than 12 months (1 year) from my table.(automate through SP to keep only rolling 12 months data), but the problem is the field 'LoadedDate' is in YYYYMM (201808)(varchar) format.(This field is actually the date to tell which month's data it is..... not like the date it was loaded in the table as the data insert is pretty random throughout the months) Thanks in advance [/INST]If I get this right: DELETE tbl WHERE LoadedDate < (SELECT convert(char(6), MAX(convert(int, LoadedDate)) - 100) FROM tbl That is, convert the highest value of LoadedDate to integer, deduct 100 to go back one year. (This is a little shortcut, and would not work well if the limit was 15 or 18 months.)</s>
<s>[INST]SQL21 Release and Benefits to SQL19 Good day, I am planning an upgrade in 3 months, was looking at SQL19 with VS19 Communit SSDT 1. I have read SQL21 is on the cards, when would is the release? 2. Benefits from Upgrades from sql19 to sql21 > im looking for speed and paralism fixes? 3. Do i wait for patch to be released before upgrading? 4. Different in lsence cost from sql2014 enterprise to sql21 enterprise? Regards[/INST]I have read SQL21 is on the cards, when would is the release? There is no public information on if and or when the next major release of SQL server will occur. > Benefits from Upgrades from sql19 to sql21 \> im looking for speed and paralism fixes? Since the product has not been officially announced, there is no information for this. > Do i wait for patch to be released before upgrading? This is your personal preference. You should be patching to the latest versions, always. > Different in lsence cost from sql2014 enterprise to sql21 enterprise? Again, since there is no public information there may or may not be a change in licensing for vNext.</s>
<s>[INST]SQL Server Create Database Defaults (additional sets) I have posted a previous question with the same title, but below are the last lot of defaults I have found which go against what you would expect for a database default. Is this again for backward compatibility, and is over-ridden by the connection? Or should I actively change? SET CONCAT_NULL_YIELDS_NULL OFF SET NUMERIC_ROUNDABORT OFF SET QUOTED_IDENTIFIER OFF[/INST]Leave them alone. These settings only matters if you connect with very old APIs like DB-Library. Moden APIs connect with these settings ON, and OFF for the database option does not change that. But DB-Library connects with these settings OFF, and you can change that by setting the options to ON.</s>
<s>[INST]How to use different date comparisons based upon a value in sql I have to write an update query. If the special_member account is not canceled then in the where clause I have to use this condition by adding a grace period of 15 to the expiry date and compare it today's date: Convert(date,MEMBER_EXPIRY_DATE + 15) >= Convert(date,GETDATE()). If the membership is canceled then I have to compare with actual expiry date with today's date. This is my full query: UPDATE SPECIAL_MEMBER SET SAVINGS_PERCENT = 10, ORDER_COUNT = 1 WHERE SPECIAL_MEMBER = '4382' AND CASE WHEN (CANCELLED = 0) THEN Convert(date,MEMBER_EXPIRY_DATE + 15) >= Convert(date,GETDATE()) ELSE (Convert(date,MEMBER_EXPIRY_DATE) >= Convert(date,GETDATE())) END When I execute it I am getting Incorrect syntax near '>' Thanks[/INST]You can not use a CASE condition in this way in a WHERE clause, you need at least a real compare. You can re-write the query with boolean logic like this UPDATE SPECIAL_MEMBER SET SAVINGS_PERCENT = 10, ORDER_COUNT = 1 WHERE SPECIAL_MEMBER = '4382' AND ((CANCELLED = 0 AND Convert(date,MEMBER_EXPIRY_DATE + 15) >= Convert(date,GETDATE()) OR (CANCELLED <> 0 AND Convert(date,MEMBER_EXPIRY_DATE) >= Convert(date,GETDATE()))</s>
<s>[INST]Error when programming RMO for SQL 2019: MissingMethodException Hello, I'm trying to execute the following lines of C# code: var connection = new Microsoft.Data.SqlClient.SqlConnection(@"Server=.;Database=master;Integrated Security=true;"); var serverConnection = new Microsoft.SqlServer.Management.Common.ServerConnection(connection); var replicationServer = new Microsoft.SqlServer.Replication.ReplicationServer(serverConnection); bool installed = replicationServer.DistributorInstalled; But this code crashes on the last line, where the DistributorInstalled property is being read. I'm getting a MissingMethodException: Method not found: 'System.Data.SqlClient.SqlDataReader Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteReader(System.String)'. I added the following references to this project: - NuGet package 'Microsoft.SqlServer.SqlManagementObjects' version 161.44091.28 (this is the last version at the time of writing) - C:\Program Files (x86)\Microsoft SQL Server\150\SDK\Assemblies\Microsoft.SqlServer.Rmo.dll - C:\Program Files\Microsoft SQL Server\150\SDK\Assemblies\Microsoft.SqlServer.Replication.dll I also tried switching the Microsoft.SqlServer.Rmo and Microsoft.SqlServer.Replication libraries with versions from the GAC but this doesn't help. I keep getting the same error message. Can anyone provide some help please? Thanks, Stefan Adriaenssen [/INST]The Replication libraries installed as part of the SQL Server install need to be paired with an older, compatible version of SMO. The version of SMO you are using has switched from the .NET Framework SqlClient (System.Data.SqlClient) to the newer standalone one (Microsoft.Data.SqlClient). So downgrade the SMO NuGet package to 150.18208.0, and change the code to : var connection = new System.Data.SqlClient.SqlConnection(@"Server=.;Database=master;Integrated Security=true;"); var serverConnection = new Microsoft.SqlServer.Management.Common.ServerConnection(connection); var replicationServer = new Microsoft.SqlServer.Replication.ReplicationServer(serverConnection); bool installed = replicationServer.DistributorInstalled;</s>
<s>[INST]Date filter ,just apply on Inv_Typ 'Payable'. i want to apply date filter just on Inv_Typ='Payable' ,not apply on where inv_type ='Received',below is data and query,i tried but it is applying on both inv_type. Create table #tbl_Receivable (Rec_ID int,Inv_ID int ,Customer_ID int,Rec_Date date,Rec_Amount varchar(50),Inv_type varchar(50),item_Weight int); Create table #tbl_Customer ( Customer_ID int ,Customer_Name varchar(50)); insert into #tbl_Customer values (1,'Akhter'), (2,'Hussian'); INSERT INTO #tbl_Receivable VALUES (111,211,1,'2020-03-06',5000,'Payable',0), (112,211,1,'2020-03-07',2000,'Received',0), (113,222,1,'2020-03-08',8000,'Payable',0), (114,223,2,'2020-03-08',2000,'Payable',0), (115,222,1,'2020-03-09',4000,'Received',0), (116,224,1,'2020-03-10',15000,'Payable',500), (117,211,1,'2020-03-12',1000,'Received',0), (118,224,1,'2020-03-11',15000,'Received',0) ; declare @StartDate date = '2020-03-06'; declare @EndDate date = '2020-03-11'; ;with E1 as ( select r.*, cast(Rec_Amount as int) as amount ,Customer_Name,'' as txtRec_amt from #tbl_Receivable r inner join #tbl_Customer c on c.Customer_ID = r.Customer_ID where ((R.Rec_Date) between @StartDate and @EndDate) ), E2 as ( select Inv_ID, max(item_Weight) as item_Weight, Customer_ID, Customer_Name,txtRec_amt, min(Rec_Date) as Rec_Date, isnull(sum(case Inv_type when 'Payable' then amount end), 0) as Payable, isnull(sum(case Inv_type when 'Received' then amount end), 0) as Received from E1 group by Inv_ID, Customer_ID,Customer_Name,txtRec_amt ), E3 as ( select Inv_ID as Inv_ID0, cast(Inv_ID as varchar(10)) as Inv_ID, cast(item_Weight as varchar(10)) as item_Weight, cast(Customer_ID as varchar(10)) as Customer_ID, cast(Customer_Name as varchar(50)) as Customer_Name, cast(Rec_Date as varchar(20)) as Rec_Date, cast(txtRec_amt as varchar(50)) as txtRec_amt, Payable, Received, Payable - Received as Pending from E2 ), E4 as ( select * from E3 union all select 2147483647, '', '', '', -- 'TOTAL', '', '', '', '', '', '' --sum(Payable), --sum(Received), --sum(Pending) from E3 ) select Inv_ID,txtRec_amt, item_Weight, Customer_ID, Rec_Date, Payable, Received, Pending,Customer_Name from E4 where Pending >0 order by Inv_ID0 [/INST]What you are actually asking for is the data on a specific date range. In order to do that, you must calculate everything and filter the result. DROP TABLE IF EXISTS #tbl_Receivable; DROP TABLE IF EXISTS #tbl_Customer; Create table #tbl_Receivable (Rec_ID int,Inv_ID int ,Customer_ID int,Rec_Date date,Rec_Amount varchar(50),Inv_type varchar(50),item_Weight int); Create table #tbl_Customer ( Customer_ID int ,Customer_Name varchar(50)); insert into #tbl_Customer values (1,'Akhter'), (2,'Hussian'); INSERT INTO #tbl_Receivable VALUES (111,211,1,'2020-03-06',5000,'Payable',0), (112,211,1,'2020-03-07',2000,'Received',0), (113,222,1,'2020-03-08',8000,'Payable',0), (114,223,2,'2020-03-08',2000,'Payable',0), (115,222,1,'2020-03-09',4000,'Received',0), (116,224,1,'2020-03-10',15000,'Payable',500), (117,211,1,'2020-03-12',1000,'Received',0), (118,224,1,'2020-03-11',15000,'Received',0) ; declare @StartDate date = '2020-03-06'; declare @EndDate date = '2020-03-06'; ;with E1 as ( select r.*, cast(Rec_Amount as int) as amount ,Customer_Name,'' as txtRec_amt from #tbl_Receivable r inner join #tbl_Customer c on c.Customer_ID = r.Customer_ID ), E2 as ( select Inv_ID, max(item_Weight) as item_Weight, Customer_ID, Customer_Name,txtRec_amt, min(Rec_Date) as Rec_Date, isnull(sum(case Inv_type when 'Payable' then amount end), 0) as Payable, isnull(sum(case Inv_type when 'Received' then amount end), 0) as Received from E1 group by Inv_ID, Customer_ID,Customer_Name,txtRec_amt ), E3 as ( select Inv_ID as Inv_ID0, cast(Inv_ID as varchar(10)) as Inv_ID, cast(item_Weight as varchar(10)) as item_Weight, cast(Customer_ID as varchar(10)) as Customer_ID, cast(Customer_Name as varchar(50)) as Customer_Name, cast(Rec_Date as varchar(20)) as Rec_Date, cast(txtRec_amt as varchar(50)) as txtRec_amt, Payable, Received, Payable - Received as Pending from E2 ), E4 as ( select * from E3 union all select 2147483647, '', '', '', -- 'TOTAL', '', '', '', '', '', '' --sum(Payable), --sum(Received), --sum(Pending) from E3 ) select Inv_ID,txtRec_amt, item_Weight, Customer_ID, Rec_Date, Payable, Received, Pending,Customer_Name from E4 where Pending >0 and Rec_Date BETWEEN @StartDate and @EndDate</s>
<s>[INST]Aged Data Not Removed in SQL Server Temporal History Table ENVIRONMENT: SQL Server 2017 Enterprise running on Windows Server 2016 Standard Test Case: 1. Create 2 identical temporal tables (differ only by name) where 1 table has HISTORY_RETENTION_PERRIOD set to 1 day. The other table is set to "INFINITE" 2. Inserted 1 record in each table 3. Create a SQL Agent Job to modify the record in each table and let job run for 3 days 4. On the 3rd day, verify table with retention period of 1 day has first day of data purged in associated history table and the 2nd history table still contain data from day one. 5. Alter 2nd table to set retention period to 1 day EXPECTED: data will be purged from 2nd historical table in same manner as 1st temporal table. ACTUAL: Aged data in 2nd historical table is not removed per retention policy set. Is this expected behavior or am I missing a step in purging data in the second temporal table. [/INST]The retention policy is enforced only run once a day via the SQL Agent job "syspolicy_purge_history".</s>
<s>[INST]Actual Execution plan for query store is it possible to capture actual execution plan inside query store ? or else need to use back xevent ?[/INST]As noted already, Query Store is the estimated plan. The (at least one) reason for that is that QS aggregates data. Say that it aggregates data over, one hour as an example. And a certain query plan was used 123 times over that hour. What would you want to see in the "actual plan"? An average over those 123 executions? That would still not be the actual plan. In order for QS to be able to get the actual values, it would have to have the option to store every single execution run-stats! Imagine the overhead! And I know you can, since you are questioning that overhead when you refer to the alternative: an XE trace.</s>
<s>[INST]not able to put is equal to sign (=) in query, When i am inserting is equal sign= in query code sample then sign (=) in query is not showing in preview, what can be the issue[/INST]We faced some known issues when we tried to post one question together with some long code. Since I could not see any code from your question, you could still post one question in Feedback and wait for response. Right now you could copy and paste your query in one txt file and attach to your post instead of pasting the code in answer directly so that you could ignore this issue.</s>
<s>[INST]sql permissions to run only update stats hi all, we would like to give some business users with access to run only update stats. I am thinking of creating a role for these users and somehow assign them the rights to run "update stats" would you please share can I grant the users permisisons to run the sp_updatestats without them being in the sysasmin role. thanks a lot for help[/INST]There's no granular permission for just UPDATE STATISTICS. Instead write a stored procedure to update the stats and give them EXECUTE permissions to the procedure. eg: create or alter procedure update_stats with execute as owner as begin update statistics sometable with fullscan</s>
<s>[INST]compatibility_level and LEGACY_CARDINALITY_ESTIMATION Hi everyone, we migrated from sql 2012 to sql 2016 and since then we have been facing some performance issue. We decided to change the compatibility level to 110 (sql 2012) and set the LEGACY_CARDINALITY_ESTIMATION= ON. It helped but then we were still having performance issues and we switched back to the original configuration. Now, we lately noticed that one of the sproc which took 4 hrs finished in 35 minutes with the SET COMPATIBILITY_LEVEL = 110 and LEGACY_CARDINALITY_ESTIMATION = ON settings. I decided to turn the feature on inside the sproc and once sproc is done turn it off. But to my surprise if I do it inside sproc and then run sproc, performance is s till bad. But if i change the setting in the same session, I see a quick performance boost. So sproc is not picking up the latest DB changes. Here is my code in sproc: declare @sqlcompatiblity nvarchar(200) SET @sqlcompatiblity = N'ALTER DATABASE xm_data3 SET COMPATIBILITY_LEVEL = 110'; declare @cardinality nvarchar(200) SET @cardinality = N'USE xm_data3; ALTER DATABASE SCOPED CONFIGURATION SET LEGACY_CARDINALITY_ESTIMATION = ON;'; EXEC sp_executesql @sqlcompatiblity; EXEC sp_executesql @cardinality; WAITFOR DELAY '00:01:00'; then setting back to original setting SET @sqlcompatiblity = N'ALTER DATABASE xm_data3 SET COMPATIBILITY_LEVEL = 130'; SET @cardinality = N'USE xm_data3;ALTER DATABASE SCOPED CONFIGURATION SET LEGACY_CARDINALITY_ESTIMATION = OFF;'; EXEC sp_executesql @sqlcompatiblity; EXEC sp_executesql @cardinality; still amazed why is it working if i alter the DB in the same sql session I run the sproc. After I run the sproc, I go and check the DB, and I see settng have been changed. Any idea? Thanks, Ro [/INST]Changing the database option in a proc seems like a very weird thing to do, IMO. And I'm not surprised that it isn't picked up by the proc. One aspect is how the plan is cached, but even with recompile in the queries, I'm not surprised if that is the case. And I doubt you'll find this documented anywhere. So work with what MS wants us to use instead. In your case, since you only want it for the queries in this proc, use optimizer hints. Exactly whine one(s) depends on whether you need optimizer fixes, the cardinality estimator or optimizer enhancements. Or do trial an error. Anyhow, here are hints you can play with. Just search and you'll find out what each do and then you can use one or more accordingly: QUERY_OPTIMIZER_COMPATIBILITY_LEVEL_xxx, ENABLE_QUERY_OPTIMIZER_HOTFIXES, FORCE_LEGACY_CARDINALTY_ESTIMATION, 9481, 2312. The numbers are trace flags, but they can be turned on at query level using the QUERYTRACEFLAG hint.</s>
<s>[INST]Query takes long time to run SQL Server: 2014 Problem: I am running a query that joins 3 views and produces results. Query takes over 8 minutes to run, but it runs without an error and produces correct output. Can you please take a look at my query and tell me why it takes 8 mins for it to run? Server has no shortage of resources, all the other tasks are running without a problem. Thank you. =========================================== select DISTINCT n1.[Bill Account Number], n1.[Service Account Number], n1.[Service Customer Name], n1.[Service Street Name],--Service address n1.[Service Street Number], n1.[Apartment Number], n1.[Telephone Number], n1.[Company Name], n1.[Core Service Type], n1.[Service Status], n1.[Service Type], n2.[USEC Code], n2.[Rate Table], n2.[USEC Desc], n2.[Recurring Amount], n2.[USEC Quantity], n3.[Service Account Number], n3.[Company Name] as COMPANY FROM [dbo].[View1] AS n1 INNER JOIN [dbo].[View2] AS n2 ON n1.[Bill Account Number]=n2.[Bill Account Number] INNER JOIN [dbo].[View3] AS n3 ON n2.[Service Account Number]=n3.[Service Account Number];[/INST]We need to see the code in each view - but just with this the only thing I can say is that it doesn't have a WHERE clause and you are using DISTINCT. It would also help if you could provide the execution plan - which would help identify if there are missing indexes or statistics.</s>
<s>[INST]sql server windows ad role permisions I would like to grant a specific windows role automatic permissions to be the "dbo" every time a new database is created, can this be accomplished using the model database, thanks[/INST]Yet an alternative is to use a server-level DDL trigger that adds the role to the database when it is created. But Tibor makes a good point about databases that are restored on the server. DDL triggers don't fire on RESTORE as recall.</s>
<s>[INST]How can i deny access to any sql management from lan and public network? Hello, Can i deny access to any sql management from lan and public network? I mean the user SA to be able to be used to read and write in the bases but not to connect with the sql management or similar app. Thank you, Giorgos[/INST]you can't specify access at the application level. If a person knows how your trading program logs in to SQL Server, then that person can use the same login credential to login using SSMS and work with those same privileges. I suggest you re-read Erland's post carefully. Erland missed in "e" after a "not", so it should be "note" instead of "not", btw.</s>
<s>[INST]How to calculate 90th Percentile on time (either MM:SS or seconds ) SELECT DISTINCT ,DATEDIFF(s,MV_Incident.IncidentStartedDateTime,MV_Incident.IncidentDate) AS CalltakerProcessingTime ,DATEDIFF(s,MV_Incident.IncidentStartedDateTime,MV_Incident.FirstUnitDispatchedTime) AS TotalProcessingTime ,DATEDIFF(s,MV_Incident.IncidentDate,MV_Incident.FirstUnitDispatchedTime) AS GatekeeperProcessingTime FROM MV_Incident I am attempting to calculate the 90th percentile for time frames obtained from DATEDIFF. I am open to doing this in either the syntax of the query or in an expression in Report Builder. I know it is possible to do in excel but I am hopeful there is a way to achieve this automatically with a query or expression. I am looking at a list of results like this: 03:11 02:09 01:35 00:57 02:36 90th percentile 02:57 (according to excel). [/INST]Here is an example of how you can do this. I remove the DISTINCT, because DISTINCT could have some interesting effects when computing percentiles. ; WITH CTE AS ( SELECT DATEDIFF(s,MV_Incident.IncidentStartedDateTime,MV_Incident.IncidentDate) AS CalltakerProcessingTime, DATEDIFF(s,MV_Incident.IncidentStartedDateTime,MV_Incident.FirstUnitDispatchedTime) AS TotalProcessingTime, DATEDIFF(s,MV_Incident.IncidentDate,MV_Incident.FirstUnitDispatchedTime) AS GatekeeperProcessingTime FROM MV_Incident ), percenttiles AS ( SELECT percentile_cont(0.9) WITHIN GROUP (ORDER BY CalltakerProcessingTime) OVER() AS CalltakerProcessingTime, percentile_cont(0.9) WITHIN GROUP (ORDER BY TotalProcessingTime) OVER() AS TotalProcessingTime, percentile_cont(0.9) WITHIN GROUP (ORDER BY GatekeeperProcessingTime) OVER() AS GatekeeperProcessingTime FROM CTE ) SELECT TOP (1) GatekeeperProcessingTime, TotalProcessingTime, GatekeeperProcessingTime</s>
<s>[INST]Best way to create a second instance current and available 24x7. Hi everyone! What would be the best solution to make a production database available to another SQL Server instance (on a different server) in read-only mode, without interruptions? I mean, current and available 24x7. Mirror, replication, etc. Hope I was clear enough. [/INST]Microsoft SQL Server 2017 (RTM-CU16) (KB4508218) - 14.0.3223.3 (X64) Jul 12 2019 17:43:08 Copyright (C) 2017 Microsoft Corporation Standard Edition (64-bit) on Windows Server 2016 Datacenter 10.0 \<X64> (Build 14393: ) (Hypervisor). Since you have standard SQL Server 2017 Full fledged AG is rules out and if you configure Basic Availability Groups (BAG) you would not get readable secondary. So you are left with 2 options 1. Transaction log shipping with secondary server is Standby/Read only mode. Here whenever restore happens from primary the running connections would be terminated to take exclusive lock for restore 2. Transactional replication. Will have your copy of database but has some inherent limitations. See books online.</s>
<s>[INST]Concurrency question Hi, I need to make sure that 2 connections to the table never get the same id for processing... For example: create table dbo.concurrency(id int identity, task varchar(80), status varchar(80)) go insert dbo.concurrency(task, status) values('task A','active') insert dbo.concurrency(task, status) values('task B','active') insert dbo.concurrency(task, status) values('task C','active') insert dbo.concurrency(task, status) values('task D','active') go Both connections run the same transaction: begin tran declare @id int select @id = min(id) from dbo.concurrency where status = 'active' update dbo.concurrency set status = 'pending' where id = @id commit tran I want to make sure that the moment 1st connection starts transaction and choses id = 1 for update (at the select statement, and before update and commit), 2nd transaction cannot chose id = 1, but the next one, id = 2 for update of status. This cannot be achieved by setting transaction isolation level (any of them), as even if we chose the most restrictive one of them, SERIALIZABLE, if we run the 2nd transaction before update statement of the 1st transaction, both will update id = 1 row: connection 1 will update it once, and connection 2 will update it 2nd time as its select was not blocked by 1st connection select. Any idea?[/INST]How about an UPDLOCK on the SELECT? That should hold an update lock on the row, forcing the other one to wait. One could even imagine using READPAST, making the other ignore the row(s) with conflicting lock (pick the "next" one) - but you'd want to play a bit with that to make sure my reasoning isn't just because lack of coffee (yet).</s>
<s>[INST]Always-on : Log Send Queue THere is a performance counter for Always-on Log Send Queue The amount of log records in the log files of the primary database, in kilobytes, that are not yet sent to the secondary availability replica. which means it shows only the data lost for async replica ? [/INST]which means it shows only the data lost for async replica ? You can say that because primary will not wait for the commit on secondary and if primary goes down and these logs are not sent to secondary and you being up secondary this information would not be there and that would be a data loss to you. That is one of the prime disadvantage of Async mode</s>
<s>[INST]How to run sql agent job in ssms every 30 minutes except during a certain time? I have a Sql server agent job which currently runs every 30 minutes, every day, etc. I'd like to modify it so that it will run every 30 minutes, every day except between 7:00 pm and 11:30 pm. Is this possible with the job scheduler? [/INST]Simply test on the current time in the job, like IF NOT CONVERT(time, GETDATE()) BETWEEN '19:00:00' AND '23:30:' BEGIN -- Do the job SELECT 1</s>
<s>[INST]Find leaf level from organization table Hi! I need to find leaf levels in an organizational table with some type of query. The rownr are unike. But the leaf level could be found in any level and consist of one or multiple rows before going up one one or many levels and then down to leaf level again. In this example i would like to find rownr, 3, 4, 8, 10 and 11. But my table consist of some thousand units but if a query could find leaf levels for this example i think it should work for table also. I have tried to solve this but i cant find a solution so i hope someone can help me. Br Arne The structure looks like below Rownr Level 1 1 2 2 3 3 4 3 5 2 6 3 7 4 8 5 9 4 10 5 11 5 [/INST]Create Table #Sample(Rownr int, Level int); Insert #Sample(Rownr, Level) Values (1, 1), (2, 2), (3, 3), (4, 3), (5, 2), (6, 3), (7, 4), (8, 5), (9, 4), (10, 5), (11, 5); ;With cte As (Select s.Rownr, Level, Lead(s.Level) Over(Order By s.Rownr) As NextLevel From #Sample s) Select c.Rownr From cte c Where c.Level >= IsNull(c.NextLevel, c.Level) Order By Rownr; go Drop Table #Sample;</s>
<s>[INST]What must updated null flag updated or conflict flag updated? I work on SQL server 2012 .really I don't understand what statement below do updatedand when when NullFlag updated and when conflict flag updated can you explain to me according to sample below result of query data details rows without grouping Masked_ID DocumentID PartID NULLCount 29283933 76724 31345983 NULL 29283933 76724 31345984 NULL 29283933 76724 31345985 NULL 29283933 76724 31345986 NULL 29283933 NULL NULL 1 29283933 NULL NULL 1 29283933 76724 31345989 NULL 29283933 NULL NULL 1 29283933 NULL NULL 1 29283933 76724 31345992 NULL UPDATE FFFF SET Conflictflag= IIF((NotNULL+NuLLCount)<>RowsCount AND Ex.MaskExceptionID IS NULL ,CONCAT(Conflictflag,'PCN','|'),Conflictflag), NULLflag=IIF((NotNULL+NuLLCount)=RowsCount AND NuLLCount>0 AND NULEX.NULLExceptionID IS NULL,CONCAT(NULLflag,'PCN','|'),NULLflag) FROM ( --SELECT Masked_ID,SUM(CNT)/COUNT(DocumentID) AS NotNULL ,SUM(NULLCount)AS NuLLCount SELECT Masked_ID,SUM(CNT)/nullif(COUNT(DocumentID),0) AS NotNULL ,SUM(NULLCount)AS NuLLCount FROM ( SELECT FF.Masked_ID, LC.DocumentID, COUNT(DISTINCT LC.PartID) AS CNT, COUNT( CASE WHEN DocumentID IS NULL THEN 1 ELSE NULL END )NULLCount FROM ExtractReports.dbo.MultiMask FF INNER JOIN Parts.Nop_Part ptt WITH(NOLOCK) ON ptt.Masked_ID=ff.Masked_ID LEFT JOIN PCN.DocumentParts LC WITH(NOLOCK) ON ptt.PartID=LC.PartID WHERE FF.PCNs LIKE '%|%' GROUP BY FF.Masked_ID ,LC.DocumentID )DD GROUP BY DD.Masked_ID ) DDFF INNER JOIN ExtractReports.dbo.MultiMask FFFF ON DDFF.Masked_ID=FFFF.Masked_ID LEFT JOIN [ConflictReport].dbo.MaskExceptions EX ON EX.MaskID=FFFF.Masked_ID AND EX.FunctionName='PCN' LEFT JOIN [ConflictReport].dbo.NULLExceptions NULEX ON NULEX.MaskID=FFFF.Masked_ID AND NULEX.FunctionName='PCN' WHERE FFFF.PCNs LIKE '%|%' on case of data above what must updated Null flag or conflict flag and why can you please help me [/INST]The seq is name of one cte , not a function. Please use the complete query as below: ;with cte as ( select max(PartID) max,min(PartID) min from [DocumentParts] group by DocumentID) ,seq(n) AS ( SELECT min from cte UNION ALL SELECT n + 1 FROM seq WHERE n < (select max from cte) ) select * from seq You could consider to use multiple CTE as below: ;with cte as( select * from table) ,cte1 as ( select * from cte) select * from cte1</s>
<s>[INST]Datetime Convert I am using the CONVERT function in TSQL to get a date, time and AMPM as follows CONVERT(CHAR(20), CURRENT_TIMESTAMP, 22) but it gives me 08/07/20 4:41:48 PM Is there a setting that would give only 4:41 PM without the seconds? [/INST]If no such feature, then consider two alternatives: -- Method 1 declare @s as varchar(max) set @s = CONVERT(CHAR(20), CURRENT_TIMESTAMP, 22) set @s = STUFF( @s, PATINDEX('%:[0-9][0-9] [AP]M', @s), 3, '') select @s -- Method 2 select FORMAT( CURRENT_TIMESTAMP, 'dd''/''MM''/''yy h'':''mm tt') The date part can be removed if not needed.</s>
<s>[INST]Old version SQL server license questions We have some SQL servers on prior 2012 versions (1 version 2005 and 5 versions 2008 R2, standard editions)  still being used for our business, I have two questions: 1. Microsoft extended support for 2005 and 2008 R2 version SQL server  has already ended by now,  do the old versions SQL servers above still need license compliance? 2. Per core based SQL server license model started for version 2012 servers and after, if 2005/2008 version SQL servers still need license compliance, do we have to use service/CAL based license to cover these old servers? Thank you [/INST]Microsoft extended support for 2005 and 2008 R2 version SQL server has already ended by now, do the old versions SQL servers above still need license compliance? Yes ofcourse, does not supported does not means you can run anything without proper license. > Per core based SQL server license model started for version 2012 servers and after, if 2005/2008 version SQL servers still need license compliance, do we have to use service/CAL based license to cover these old servers? Server/CAL based license is still their, so you need to use that. Speak to local Microsoft Licensing Specialist.</s>
<s>[INST]SQL Server database backup Hi Expert, We are not taking any Full backup for databases except TLog backup. Commvault backup is running every day on most of the production Server and I asked Commvault Admin to verify how it is running. He said Commvault is taking only Disk level backup such as MDF and LDF. In terms of disaster they can only restore MDF and LDF and Tlog backup. If Commvault can't bring the database nonrecovery then all Tlog backup will be pointless in my understanding. Should I rely on this kind of backup? Please clarify me Thank You,[/INST]If Commvault can't bring the database nonrecovery then all Tlog backup will be pointless in my understanding. Yes you are correct, unless Comm Vault takes proper full backup the log backups you are taking is useless. A disk level backup which means basically taking copy of mdf and ldf files will not help in point in time recovery. > Should I rely on this kind of backup? Please clarify me Basically that depends on RPO and RTO but in most cases this is not good backup policy. If Comm Vault would have been taking "proper" SQL Server full and log backups it would have been reliable but disk level backups are only always considered as secondary backups. I would suggest you to talk with Comm vault team and see if they can start taking proper backups, if not, you start taking SQL Server backups using TSQL or Maintenance plans.</s>
<s>[INST]How to count Leadfinish where have values and not null ? I work on SQL server 2012 I Face issue I can't count values on Lead finish in case of no null so How to do that Please ? so suppose I have values on LeadFinishPlatingID as : companyID LeadFinishPlatingID 345 12333 345 45678 345 23323 345 NULL Then count for leadfinishPlatingID will be 3 for company id 345 so i need to modify sql script below to count only not null on LeadFinishPlatingId based on company id SELECT Companies.DisplayName CompanyName, ISNULL(Data.CNt, 0) AS TotalPartsCount, ISNULL(Data.CNt - ISNULL(df.ManCount, 0), 0) AS [Parts Difference], ISNULL(df.ManCount, 0) ManufacturingPartsCount, ISNULL(df.[LeadFinishPlating], 0) [LeadFinishPlating] FROM ( SELECT CompanyID, COUNT(PartID) CNt FROM Parts.Nop_Part GROUP BY CompanyID )AS Data LEFT JOIN ( SELECT p.CompanyID, COUNT(m.PartID) ManCount, COUNT(m.LeadFinishPlatingID) as [LeadFinishPlating] from Parts.ManufacturingData m LEFT JOIN Parts.Nop_Part p ON p.PartID = m.PartID GROUP BY p.CompanyID )AS DF ON Df.CompanyID = Data.CompanyID LEFT JOIN ( SELECT c.CompanyComID, C.DisplayName FROM dbo.core_company c )AS Companies ON Companies.CompanyComID = Data.CompanyID [/INST], Please refer to: ;with cte as(select *,row_number() over(partition by LeadFinishPlatingID order by LeadFinishPlatingID) rn from Parts.ManufacturingData) SELECT Companies.DisplayName CompanyName, ISNULL(Data.CNt, 0) AS TotalPartsCount, ISNULL(Data.CNt - ISNULL(df.ManCount, 0), 0) AS [Parts Difference], ISNULL(df.ManCount, 0) ManufacturingPartsCount, ISNULL(df.[LeadFinishPlating], 0) [LeadFinishPlating] FROM ( SELECT CompanyID, COUNT(PartID) CNt FROM Parts.Nop_Part GROUP BY CompanyID )AS Data LEFT JOIN ( SELECT p.CompanyID, COUNT(m.PartID) ManCount, COUNT(m.rn) as [LeadFinishPlating] from cte m LEFT JOIN Parts.Nop_Part p ON p.PartID = m.PartID GROUP BY p.CompanyID )AS DF ON Df.CompanyID = Data.CompanyID LEFT JOIN ( SELECT c.CompanyComID, C.DisplayName FROM dbo.core_company c )AS Companies ON Companies.CompanyComID = Data.CompanyID</s>
<s>[INST]While loop is too slow in sql to get last 3 weeks data. Getting last 3 weeks data by using while loop but its too slow. Declare @beginDate int = 0; Declare @pendDate int = 1; Create Table #NOC(WeekDates date,PeopleID int,DatefBirth date,Age int,Operator varchar(8),Location varchar(250),SA1 bigint,NOC int) While (@beginDate < 2 and @pendDate < 3) Begin Insert Into #NOC Select DATEADD(WEEK, -1 * @beginDate ,GETDATE()) , M.PeopleID, P.DateOfBirth, DateDiff(yy,P.DateOfBirth,GetDate()) as Age, m.Operator, M.LocationName, P.SA1, sum(case when M.ActiveEnd BETWEEN DATEADD(WEEK, -1 * @beginDate ,GETDATE()) and DATEADD(WEEK, -1 * @pendDate ,GETDATE()) then 1 else 0 end) From AX.Memberships M Join AX.People P On P.PeopleID = M.PeopleID and P.Operator = M.Operator Group by M.PeopleID,P.SA1,P.DateOfBirth, m.Operator, M.LocationName Set @beginDate = +1 Set @pendDate = +1 End Select * from #NOC [/INST]Your syntax for adding 1 to the variables is incorrect. It should be either Set @beginDate += 1 Set @pendDate += 1 or Set @beginDate = @beginDate + 1 Set @pendDate = @pendDate + 1 The syntax you have just sets the values to 1 every time through the loop, so your WHILE condition is never satisfied and you have an infinite loop.</s>
<s>[INST]Clone sql server and use developer edition? I have a production enterprise 2019 sql server and I want to create a dev environment of this server by cloning it using Hyper-V. I am wondering if the SQL Developer edition license would allow me to run this dev environment without purchasing another enterprise 2019 license. It would technically have *some* production data so end users can validate they are getting the same results on dev and prod, but it will be a pure dev environment, with only a handful of people accessing a few times a month. Please don't refer me to a reseller, I know how to be redirected to a reseller. [/INST]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]List with required settings per object Dear colleagues, Is there a list or table available with the required settings per database object? I know the required settings for, say, a filtered index. It would be nice, however, to know which constructions I cannot use when, for instance, ANSI_WARNINGS = OFF. Thank you for your time, Chris Sijtsma[/INST]Why would be nice to know? You should never fiddle with these settings anyway. From memory, ANSI_WARNINGS must be on for : - Indexed views. - Indexed computed columns. - filtered indexes. - spatial and xml indexes. - xml type methods and XQuery. - Heterogenous queries over linked servers.</s>
<s>[INST]Multiple server names in list Ever since upgrading to SQL Server 2019 and SSMS 18.6, when I sign in, the dropdown list of server names (in the authentication window) is doubled. I have 2 instances defined. Now I each of them twice for a total of 4 instances in the list. Everything seems to work okay, but it's annoying to have the extras. Why are they there? Can I get rid of the duplicates?[/INST]The way mentioned by JeffreyWilliams-3310 is the easiest way for SSMS 18.6 to clear items from this list.Just describe in detail: 1. Open the Microsoft SQL Server Management Studio (SSMS). 2. Open the Connect to Server dialog (File->Connect Object Explorer, Object Explorer-> Connect-> Database Engine, etc). 3. Click on the Server Name field drop down list’s down arrow. 4. Hover over the items you want to remove. 5. Press the delete (DEL) key on your keyboard. In addition, according to my test, if the windows authentication and SQL Server authentication are both used to log in to the instance, duplicate server names will appear in the server name list in SSMS 18.6 (also 17.9.1), which is a design behavior.</s>
<s>[INST]How to select data based dynamically based on start and end of AffectedProduct ? I work on SQL server 2012 I need to get data from #partsdata table where part number matches Affected Product both start and End as Example where I have Affected Product as APAMS-\*\*\*G then I will get Parts That have start APAMS- and End by G start must be end with dash (-) this roles applied to another rows on search data table . I get part number that have matched with start f affected product and end with same charachter of affectedproduct create table #searchdata ( Id int, AffectedProduct nvarchar(50) ) insert into #searchdata(Id,AffectedProduct) values (1,'APAMS-***G'), (2,'APg-***F'), (3,'Dom-***D') create table #PartsData ( PartId int, PartNumber nvarchar(50) ) insert into #PartsData(PartId,PartNumber) values (233,'APAMS-234G'), (501,'APAMS-901G'), (909,'APAMS-901G'), (700,'APg-670F'), (550,'APg-G3DF'), (940,'APg-321F'), (702,'Dom-670D'), (710,'Dom-G3DD'), (770,'APg-321L'), (915,'APAMS-901M'), (922,'APg-325N') Expected Result PartId PartNumber 233 APAMS-234G 501 APAMS-901G 909 APAMS-901G 700 APg-670F 550 APg-G3DF 940 APg-321F 702 Dom-670D 710 Dom-G3DD so How to do that please ? [/INST]Please refer the updated query from below and check whether it is working. If not, please provide more sample data with different conditions and expected output. select a.PartId,a.PartNumber from #PartsData a inner join #searchdata b on a.PartNumber like left(AffectedProduct,Charindex('-',AffectedProduct))+ replace(right(AffectedProduct,len(AffectedProduct)-(Charindex('-',AffectedProduct))),'*','_') Or select a.PartId,a.PartNumber from #PartsData a inner join #searchdata b on a.PartNumber like left(AffectedProduct,Charindex('-',AffectedProduct)) --second part after '-' like *** +replace(substring(AffectedProduct,Charindex('-',AffectedProduct)+1,len(AffectedProduct)-(Charindex('-',AffectedProduct))-1),'*','_') +RIGHT(AffectedProduct,1)</s>
<s>[INST]Legacy SQL DB question - Windows 2003, SQL 2000 instance Hi all I'm getting rid of a few Windows 2003 Servers littering this estate I've just started managing, and 100's of Windows 2008 servers. On a specific Windows 2003 server I have around 15 Databases on SQL version 8 (SQL 2000). The owner of the data tells me these DB's are for a legacy service that has been moved away from, but they want to keep the data for legal\compliance reasons. Now I could get into that with him, and ask why the data was not moved onto the replacement system (or if it indeed was), but to build up some options, could you help me figure out an approach: 1.) My thougth was to backup the 15 DB's locally, then copy that backup onto archive storage or into a Data Lake in Azure. 2.) However, considering these are SQL 2000 generated DB's......what are the options for accessing that data if it was ever required in say 5\10 years? Should we actually be looking at a data migration out of these SQL 2000 DB's first, into a newer SQL DB, and then backup and archive.....or are there means to still restore a SQL 2000 DB backup file into newer versions of SQL like 2017. Or.....worst case......if they really needed access to this data in fior example 10 years, could I just offer up that the SQL backups will be available, but they would need to engage the help of a SQL DBA to extract data in a raw and *dirty* format going forward. Any guidance appreciated. We have SQL DBA's on hand from an external support vendor if I really needed to progress it that way first, and I can then tell the Data owner that he will have to cough up the cash to have them progress this for him. Coop[/INST]Should we actually be looking at a data migration out of these SQL 2000 DB's first, into a newer SQL DB, and then backup and archive..... Yes correct that would be correct approach. > or are there means to still restore a SQL 2000 DB backup file into newer versions of SQL like 2017. No you cannot restore SQL Server 2000 DB backup directly no SQL Server 2017. You have to first upgrade to SQL Server 2008 r2/2008/2005 ( I would suggest SQL Server 2008 R2) and then move to SQL Server 2017. As I see here if you need the databases data after every 5-10 years then you must upgrade the database to latest version SQL Server 2019 and then take backup on tape and store the tapes. You have to repeat above task to make sure data is moved on latest version and stored. Don't worry about restoring database. It is not a cumbersome task. A simple google search will help you in restore if needed. **EDIT**: From questions you posted later > If I were to take a backup of a Windows 200 Database, and then try to restore it to a Windows 2017 SQL instance, for example, then would that Database just not restore at all? Yes you would not be able to restore. Moving data out from table is little tricky task as compared to restore. > I presume that is needed because in every one of those stages there are new Database schema additions\attributes added to the customer databases along the way? And without those additions at every stage, the later versions cannot mount the Databases......something like that? There is no schema addition neither any attributes that i know. The restriction is put from MS side may be because of some internal challenge which I do not know The point is you can turn it as a diff billable project to upgrade to 2019 but that is up to you and your business. The thing is later even of you have .bak file for SQL Server 2000 unless you have 200 DB engine you would not be able to read it. So put that in front of client, inform him about all the risk and let him take decision.</s>
<s>[INST]Create users(AD) for Alwayson enviroment Hi our environment is SQL Server 2016 SP2 CU14 Enterprise /Wndows 2012 R2 and Always on setup. Looking to have application users to create which need to remain permission same of the database same as prod primary and not blow away every time when failover fail back / or need database users need to match same SID on the both instances (primary and secondary ) or need to run following every time when failover /failback But AD user will remain same permission when do a failover/failback scenario use databasename go sp_change_users_login Auto_Fix, [dbuserSql]; ++++++++++++++++++++++++++++++ Q1. What is the recommended to have users in alwayon env whether to have AD user or database user for the application to connect through AG Listener (Expecting to work smoothly with no any issue with the permission ) Many thanks for the advice thanks [/INST]What is the recommended to have users in alwayon env whether to have AD user or database user for the application to connect through AG Listener (Expecting to work smoothly with no any issue with the permission ) I think you need to first understand difference between user and login. To simply put A user uses a login to connect to database. A login is server level object while user is database level object. When you mirror, restore, replicate a database users move but logins do not as they are stored in master database. Also note that `Security Identifier( SID) binds users to login`, its not binded by any name which most people think. If you create a AD account ( a domain account) its SID will be same through out the domain. And further if this AD account is added as login in SQL Server and mapped to a user they would be binded by this SID. Now post failover, this AD login will exists on secondary replica, or mirror database log secondary logshipped database if you have created it before hand ( you can do that as logins are created in master database) and `will automatically bind with user present in database and you would not see login failure or orphaned user`. So to solve your problem and if you really do not want to use `sp_change_users_login` to map logins to users I suggest you ONLY use AD account as login in SQL Server. This AD account will work just fine with listener also.</s>
<s>[INST]Incorrect syntax error near 1059 when build dynamic query? I work on SQL server 2012 I face issue error say incorrect syntax near 1059 when build dynamic query I try to build query dynamic 'Series' as [Series], 'Number of DAC's (1059)' as [Number of DAC's (1059)], 'Number of Bits (153)' as [Number of Bits (153)], 'Sampling Rate (Per Second) (348)' as [Sampling Rate (Per Second) (348)], 'Data Interface (243)' as [Data Interface (243)], 'Settling Time (2190)' as [Settling Time (2190)], 'DAC Type (1060)' as [DAC Type (1060)], 'Supplied Contents (985)' as [Supplied Contents (985)], 'Utilized IC / Part (984)' as [Utilized IC / Part (984)], 'Datasheet URL' as [Datasheet URL], 'Comments' as [Comments], 'Notes' as [Notes] [Series],[Number of DAC's (1059)],[Number of Bits (153)],[Sampling Rate (Per Second) (348)],[Data Interface (243)],[Settling Time (2190)],[DAC Type (1060)],[Supplied Contents (985)],[Utilized IC / Part (984)],[Datasheet URL],[Comments],[Notes] statement below generate text above :slight_smile: DECLARE @Header nvarchar(max)=( select substring( ( Select ', '''+ ST1.DkFeatureName +''' as ['+ ST1.DkFeatureName +']' AS [text()] From @sh ST1 order by DisplayOrder For XML PATH ('') ,TYPE).value('(./text())[1]','NVARCHAR(MAX)'), 2, 10000) [Columns]) so How to modify dynamic SQL above to avoid display this issue or this error ? [/INST]A refinement of Viorel's suggestion: Select ',' + QUOTENAME(ST1.DkFeatureName, '''') + ' as ' + QUOTENAME(ST1.DkFeatureName) AS [text()] QUOTENAME is an essential function to preserve your sanity when you work with constructing dynamic SQL.</s>
<s>[INST]Always Encrypted Testing We want to test setting up an Always Encrypted database and set columns as needed. Can we revert back to unencrypted after testing is done?[/INST]you can backup the database prior to testing and then restore a backup. (You don't have to drop the database first.) Everything about Always Encrypted is stored inside the database, so if you restore a backup, all traces are gone.</s>
<s>[INST]Adding data code run without error, yet datat didn't added into Database, just temporarily on testing. HI As per subject. this is my code private void Form2_Load(object sender, EventArgs e) { koneksicustomer = new SqlConnection("Data Source=.;AttachDbFilename=R:\\future\\STB KA SJ\\STB KA SJ\\Customer.mdf;Integrated Security=True"); koneksicustomer.Open(); commandcustomer = new SqlCommand("Select * from CustomerTable", koneksicustomer); adaptorcustomer = new SqlDataAdapter(); adaptorcustomer.SelectCommand = commandcustomer; tabelcustomer = new DataTable(); adaptorcustomer.Fill(tabelcustomer); textBox1.DataBindings.Add("Text", tabelcustomer, "CompanyName"); textBox2.DataBindings.Add("Text", tabelcustomer, "Address1"); textBox3.DataBindings.Add("Text", tabelcustomer, "Address2"); textBox4.DataBindings.Add("Text", tabelcustomer, "Address3"); managercustomer = (CurrencyManager)this.BindingContext[tabelcustomer]; private void Form2_FormClosing(object sender, FormClosingEventArgs e) { try { SqlCommandBuilder customeradaptorcommand = new SqlCommandBuilder(adaptorcustomer); adaptorcustomer.Update(tabelcustomer); } catch (Exception ex) { MessageBox.Show("error" + ex.Message, "Save Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } koneksicustomer.Close(); koneksicustomer.Dispose(); commandcustomer.Dispose(); adaptorcustomer.Dispose(); tabelcustomer.Dispose(); } private void button3_Click(object sender, EventArgs e) { try { SqlCommandBuilder customeradaptorcommand = new SqlCommandBuilder(adaptorcustomer); adaptorcustomer.Update(tabelcustomer); } catch (Exception ex) { MessageBox.Show("error" + ex.Message, "Save Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } koneksicustomer.Close(); koneksicustomer.Dispose(); commandcustomer.Dispose(); adaptorcustomer.Dispose(); tabelcustomer.Dispose(); managercustomer.EndCurrentEdit(); SetState("Lihat"); MessageBox.Show("tersimpan.", "save", MessageBoxButtons.OK, MessageBoxIcon.Information); so, supposedly i fill my textboxt data and click button 3 to perform update to my database, but after closing the database, the data is still the old one. which i have put twice update at different part of my code. anything wrong with these code? as i compare to my tutorial book, the code is exactly the same, i am just trying to declare my own variable. [/INST]Since you tagged this with an sql-server tag and not an appopriate .NET tag, you will get an SQL Server answer. Use Profiler to see that adaptorcustomer.Update command actually performs. That is what I would do if had this code, because I don't know what this adaptor thing does. Maybe it tries to do something magic. Or maybe it fails to guess your intentions. Personally, I would just have crafted an UPDATE statement and submitted that through ExecuteNonQuery.</s>
<s>[INST]Cannot setup a linked server Hi, I am trying to set up a linked server from a standalone SQL server to a 2 node Clustered SQL instance using a SQL login. It works fine from the SQL Cluster to the standalone server, but I get a 'login failed for user X' when creating it on the standalone to the clustered instance. Even if I grant the login sysadmin on the clustered instance it still fails. Any ideas what im doing wrong?[/INST]Did you look in the SQL Server error log on the SQL Cluster? There should be more details explaining why the login failed.</s>
<s>[INST]Best way to create a emergency online "backup" database Let's imagine a physical database running Sql Server (latest version). We are NOT 24x7. However at worst we don't want to lose anything more than 24 hours of work. Regular offsite backups are being done and that will continue independent of what we are now proposing We want a system where if the current database was to catch fire we would have a "backup" server we could switch to with minimal disruption, and that includes sending an email to users saying they need to configure clients and stuff. We don't want shared storage/cluster solutions unless we HAVE to. An analogy would be having a fileserver where we start using FS2 because FS1 has failed. We have about 16TB of data on the existing server. Jobs often run overnight and (I am told) we have a **far higher** "transaction rate" than most companies. We are a research department holding records for millions of people and the researchers run a considerable amount of statistical analysis on data on the server (the processing is not done of the server itself). Mostly reads but sometimes lots of read/writes. Is there a process where we can mirror the database to another one each night, and leave the second database in a state where we can activate it as a replacement for the first in the case of "disaster". During the night processing is likely to be occurring, so we can't take the current server down. ideally the (cough) "replication" procedure needs to be simple and we know where we stand with it. As I said we are willing to sacrifice 24 hours of data (that can be recreated). A key requirement is I can look the DB admin in the eye and say "this will have **no** impact on performance d**uring work hours**" ("minimal impact" is not acceptable). [/INST]This sounds like a perfect example of using Log Shipping. You can have the primary database the way it is right now and have a copy on another server that is restoring logs waiting for the next log and could even be read/only (would require licensing the secondary) if you wanted to. But with your requirements of not having impact during work hours, etc. I would go with Log Shipping. You can choose how often you restore on the other server, but this also serves another purpose and that is testing your backups that they are restorable.</s>
<s>[INST]How to update status to only repeated row not all rows? I work on SQL server 2012 I face issue when I have two rows repeated on companyname and familyname it update two rows to repeated have temp table when two rows repeated and this is wrong correct and desired result i need is to update status to second row repeated to 'FamilyName With CompanyName Repeated' CREATE TABLE #TempTable ( RowID INT PRIMARY KEY IDENTITY(1,1), FamilyName NVARCHAR(500), CompanyName NVARCHAR(500), [Status] Nvarchar(500) ) insert into #TempTable ( [FamilyName], [CompanyName]) select 'MAX952','Maxim Integrated' union all select 'MAX952','Maxim Integrated' UPDATE T1 SET T1.Status = 'FamilyName With CompanyName Repeated' FROM #TempTable T1 INNER JOIN #TempTable T2 WITH(NOLOCK) ON T1.RowID <> T2.RowID AND T1.FamilyName = T2.FamilyName AND T1. CompanyName = T2.CompanyName desired result FamilyName CompanyName status MAX952 Maxim Integrated NULL MAX952 Maxim Integrated FamilyName With CompanyName Repeated WRONG Result FamilyName CompanyName status MAX952 Maxim Integrated FamilyName With CompanyName Repeated MAX952 Maxim Integrated FamilyName With CompanyName Repeated [/INST]Here we go. **SQL** -- DDL and sample data population, start DECLARE @tbl TABLE ( RowID INT PRIMARY KEY IDENTITY(1,1), FamilyName NVARCHAR(500), CompanyName NVARCHAR(500), [Status] Nvarchar(500) ); INSERT INTO @tbl (FamilyName, CompanyName) VALUES ('MAX952','Maxim Integrated'), ('MAX952','Maxim Integrated'), ('MIN770','Miniature Integrated'), ('MIN770','Miniature Integrated'); -- DDL and sample data population, end ;WITH rs AS ( SELECT * , ROW_NUMBER() OVER (PARTITION BY FamilyName, CompanyName ORDER BY RowID DESC) AS seq FROM @tbl ) UPDATE rs SET rs.Status = 'FamilyName With CompanyName Repeated' WHERE rs.seq = 1; -- test SELECT * FROM @tbl;</s>
<s>[INST]Understand instance names on a SQL Cluster Hi!, I have a 2 node SQL Clustered instance. The name of the instance is PO. The two nodes of the cluster are: SQLCL1-1 SQLCL1-2 The 'Client Access Name' on the cluster is NFFBO-SQLCL1 Some of the apps and users connect to the current one using the format: SQLCL1\NLP and others use this to connect: NFFBO-SQLCL1\PO I dont see either of these names as Aliases in SQL Configuration Manager.. Can anyone tell me where these names are set as I need to build to similiar cluster Thanks, [/INST]The correct way to connect to SQL Server instance is `SQLServerNetworkName\Instance name` if you are having named instance of SQL Server. If you have default instance your connection would be just `SQLServerNetworname`. This will make sure no matter which node is owning the SQL Server resource it will always direct you to the node owning the SQL Server resource. Now let is say you have two nodes as Node1 and Node2 and currently SQL Server instance name PO is online on Node1. Then even if you connect using Node1\PO it will connect because this is node owning resource but this is not the correct way. The correct string should be `SQLServerNetworkName\PO`. > Some of the apps and users connect to the current one using the format: SQLCL1\NLP This means there is an instance NLP on node which is SQLCL1 and like I said above people may use Nodename\instanceName to connect but this is not correct way. The correct way is SQLServernetworkname\NLP assuming NLP is clustered SQL Server instance. I hope this clear things.</s>
<s>[INST]upgrading SQL Native Client 10.0 to 11.0 Hello, What is the process to upgrade from SQL Native Client 10.0 to 11.0 ? I apologize if this is a question that has been asked already. Thank you, Veena[/INST]Install the client and modify the connection string of the application to use the new client and run some tests; nothing else to consider.</s>
<s>[INST]How to get result from Update statement ? How to get result of Update statement in output statement I work on sql server 2012 update r set r.PartsLCUpdated=1,r.PartsLCDate=getdate(), r.IsValid=g.IsValid, r.HasReplacementCode=g.NewHasReplacementCode, r.JobUpdateHasreplacement=g.JobUpdateHasreplacement output Inserted.PartsLCUpdated,Inserted.PartsLCDate,Inserted.IsValid,Inserted.HasReplacementCode,Inserted.JobUpdateHasreplacement into #getfinal from replaceTest2 r with(nolock) inner join #GetDataElastic g on g.PartIDC=r.partidc and g.PartIDX=r.partidx and g.OldHasReplacementCode=r.HasReplacementCode and g.IsValid=r.IsValid I need to get result of update statement on output so How to do that please ? [/INST]You could declare a table variable called @getfinal to store the results of the OUTPUT clause into this table variable. Then you could use the OUTPUT INTO syntax in order to store the results into a table variable. Please refer below: DECLARE @getfinal table( PartsLCUpdated int, PartsLCDate datetime, IsValid varchar(50), HasReplacementCode varchar(50), JobUpdateHasreplacement varchar(50)); update r set r.PartsLCUpdated=1,r.PartsLCDate=getdate(),r.IsValid=g.IsValid, r.HasReplacementCode=g.NewHasReplacementCode, r.JobUpdateHasreplacement=g.JobUpdateHasreplacement output Inserted.PartsLCUpdated,Inserted.PartsLCDate,Inserted.IsValid,Inserted.HasReplacementCode,Inserted.JobUpdateHasreplacement into @getfinal from replaceTest2 r with(nolock) inner join #GetDataElastic g on g.PartIDC=r.partidc and g.PartIDX=r.partidx and g.OldHasReplacementCode=r.HasReplacementCode and g.IsValid=r.IsValid Select * from @getfinal</s>
<s>[INST]sql server sa account modify permisions is it possible to alter the permissions of the actual sa account in sql server[/INST]No. It is not possible to alter the permissions of the SA account in SQL Server. You can disable the sa login, if you want.</s>
<s>[INST]Find records deleted by cascade delete Environment : SQL Server 2017, Windows 10, Visual Studio 2019 C++ Hi All, When I delete a record from a table, few record are getting deleted from some other table due to cascade delete relationship. I want to know records deleted by cascade delete. Is there any way to find out those records? Thanks in advance. Regards, Vijay Kumar Singh [/INST]Do you know the column and value has been deleted, run SELECT C.* FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C WHERE DELETE_RULE = 'CASCADE'</s>
<s>[INST]Logshipping Licensing Hi, We have production database for which logshipping is configured in another server. There are two mode of logshipping - 1\) Standby mode/Read-only mode 2) Recovery mode As per my knowledge if we use secondary server (logshipping configured DB) for read-only purpose then it needs license. I want to know if we keep logshipping DB as Standby mode/Read-only mode but do not use that for read purpose then do we have to pay license? And if we made logshipping database in 'Recovery mode' then is it free of license? Regards Arif [/INST]As per my knowledge if we use secondary server (logshipping configured DB) for read-only purpose then it needs license. Yes correct, if you are running any type of query on sql server machine it has to be fully licensed. > And if we made logshipping database in 'Recovery mode' then is it free of license? This looks more correct approach. If you do not want to pay license for secondary database better keep it in recovery model. PS: Please note for you to have ability to run secondary server for LS in recovery mode and not pay license you need to purchase **software assurance( SA).** Without SA you would not get the benefit of running secondary server in recovery mode without paying for license. SA does not costs too much.</s>
<s>[INST]what Microsoft.VisualStudio.OLE.Interop corrupt Hi all, in the SQL Server Management Studio 2014, after right click a table and choose Edit top(n) Rows, this exception pop up. it used to work well until our database has moved to 2017 server. Do I need to upgrade my management studio also? thanks, TITLE: Microsoft SQL Server Management Studio ------------------------------------------------------------------------ Exception has been thrown by the target of an invocation. (mscorlib) ------------------------------------------------------------------------ ADDITIONAL INFORMATION: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. (Microsoft.VisualStudio.OLE.Interop) ------------------------------------------------------------------------ BUTTONS: OK ------------------------------------------------------------------------ [/INST]Is the reply helpful? BR,</s>
<s>[INST]Should non production SQL instances accessed with MSDN subscription be Developer Edition? Hi, I need to build 10 non-production SQL instances that will be accessed by Developers and Testers (each with an MSDN subscription). The Prod Instances are a mix of standard and Enterprise edition. Does the non-production instances have to be Developer edition or can I just use Enterprise and Standard? Thanks[/INST]\> id like to know can I use enterprise or standard edition (without paying the licence) on non-prod servers given that the only people accessing them will all have MSDN licences? Or do I have to use Developer edition? No, you can't. SQL server enterprise or standard edition are need to pay license. If you use them, you need to pay the license. For non-production environment that is only for test, suggest you using Developer edition( this edition is free).</s>
<s>[INST]How to grant Schema Owner to a user ? Hi, There is a request for becoming Schema Owner for "dbo" for a particular database. Currently, he already gets the following database role 1) db_datareader 2) db_datawriter 3) db_dlladmin He mentions that without being the Schema Owner, he cannot amend tables with PK column. Is it correct ? May I ask how to grant the Schema Owner to him OR just give him the dbo_owner right ? Thanks[/INST]that user says that he is a seasoned user. But he is revealing that is not, when he craves to be schema owner for dbo - because that is effectively the same as owning the entire database. Anyway, it seems that you can just sit on our hands. Look at the script below, which runs without errors. (The EXECUTE AS statement cause you to impersonate the seasoned user to you can test is permissions.) CREATE TABLE test (a int NOT NULL) CREATE USER seasoned WITHOUT LOGIN ALTER ROLE db_ddladmin ADD MEMBER seasoned go EXECUTE AS USER = 'seasoned' go ALTER TABLE test ADD id int NOT NULL go ALTER TABLE test ADD CONSTRAINT pk PRIMARY KEY (id) go REVERT go DROP TABLE test</s>
<s>[INST]SQL Server Stored procedure Hi All, I have around 2000 tables. I have to rename the original table as a _old_todaydate and I have to create new table with the same name of original table without data with the help of SP by passing two input parameters.. Original table: TEST Rename table shoud be: TEST_Old_todaysdate New table should be : TEST (without data) Is it possible to achive above output using SP with two input parameters? If yes, can you please SP code outlines for this. [/INST]To process one table, try something like this: create procedure MyProcedure @table_name varchar(100) as begin declare @s varchar(max) = concat('select * into ', quotename(@table_name + '_Old_' + convert(varchar(max), getdate(), 120)), ' from ', @table_name, ' truncate table ', @table_name) exec (@s) end Such things will probably not work in case of relationships between tables.</s>
<s>[INST]SQL Server 2019 Developer - help with error in Log Hi, I made the transition by attaching databases from Server 2008 to SQL Server 2019 Developer. One of the databases uses Service Broker. I noticed that in the Log file (which grew very large in a short time) the following error appeared: The activated proc '[dbo].[SqlQueryNotificationStoredProcedure-f8159ca1-beff-4e33-9328-10cfe06c36cd]' running on queue 'A102.dbo.SqlQueryNotificationService-f8159ca1-beff-4e33-9328-10cfe06c36cd' output the following: 'Could not find stored procedure 'dbo.SqlQueryNotificationStoredProcedure-f8159ca1-beff-4e33-9328-10cfe06c36cd'.' The error occurs very often for the same database but with a different GUID in the explanation. Can you tell me what I'm not doing right?[/INST]It appears that you have set up query notification somewhere, possibly with the SqlDependncy class. I don't what is going on, but you will need to dig around: See which queues you have, and which of these SqlQueryNotificationStoredProcedure you have or have not. Not the least check for errors that indicates that they cannot be created.</s>
<s>[INST]SQL Server Cursor performance - dependece of cursor type and ORDER BY clause Hi! Today I encountered an intresting problem. I have table with 2 000 000 rows of data. There are three indexes. One cluseter index [Id] and two non-clustered index [Date] and [No]. I have opened SQL Server Cursor to fetch data from DB. It was Dynamic Cursor. In first case I had statement like this: SELECT * FROM TABLE1 ORDER BY [Date],[Id] This statement executed after few miliseconds. In second case I had statement like this: SELECT * FROM TABLE1 WHERE [No] like 'ABC%' ORDER BY [Date],[Id] This statement executed after 40 seconds. Then I deleted ORDER BY clause from statement SELECT * FROM TABLE1 WHERE [No] like 'ABC%' This statement executed after few miliseconds again. Why is ORDER BY making so difference in performance? In addition, when I changed cursor type to Keyset, this problem not occured. [/INST]I did explain: I told you to stay from all other cursor types than static. But, OK, a little elaboration can be in place. STATIC is very simple: the query is executed when you run OPEN on the cursor and the result is stored in a worktable in tempdb, and the cursor is served from this table. A concept which is very simple to understand. KEYSET is similar, but only the *keys* are stored in the work table. Remaining values are taken from the live tables. This makes the cursor slower - and what is the point? I don't know. DYNAMIC - the cursor is evaluated on every FETCH, and if this sound slow to you, I don't know what that sounds slow to you. It can lead to real performance disasters. And sometimes infinite loops, I believe. FAST_FORWARD - I have never been able to understand what it does. Books Online says "like dynamic with optimizations". I don't think I have ever seen a FAST_FORWARD cursor that performed a lot worse than a static cursor, but I'm not using something I don't understand. Depending on the query, you may get a different cursor type than what you ask for. STATIC is the only one that can work with any query. Also, keep in mind that cursors is something you don't have reason to use very often. Set-based statements is almost always faster.</s>
<s>[INST]Which is faster ? View or Stored procrdeure Let's say we have we simple query to get data from a table. `select firstname from Customer` We have a View with this query and stored procedure . Which is faster and why ? [/INST]I would expect identical performance with either a view or stored procedure because the query execution plans will likely be the same. Views and procedures are different from a functionality perspective, though, so you may see differences in performance for more complex scenarios but I wouldn't generalize one will be faster than the other.</s>
<s>[INST]Bulk load data conversion error (truncation) Hello, we have a SQL Server Agent job that successfully BULK Insert from a .txt file when created by Windows machine. App team is changing their process to create this same .txt file but via Linux. But when I run the same job with same .txt file created from Linux (looks like exact same formatting visually and see no difference) our SQL Agent job fails mentioning: Bulk load data conversion error (truncation) for row 1, column 7 (Column_Name). [SQLSTATE 42000] (Error 4863). The step failed. I noticed column 7 is the very last column in .txt file. Could it be some hidden carriage return command and/or how Linux generates this .txt file and how to make it compatibile from Linux end (extra parameter command/config syntax)? We don't want to change our SQL Agent job though BULK Insert does use Format File and would consider changing .fmt. Thanks in advance.[/INST]On Windows line-breaks are usually the sequence of CR-LF (carriage return + line feed). Of also denoted as \r\n. On Unix on the other hand, line endings are usually marked by line feeds (\n) only. BULK INSERT reads a binary stream of data, so if you have set up the line ending to be \r\n, and there is no \r, BULK INSERT will simply consume that lone \n as part of the data, and then it goes downhill from there. If I understand you correctly, you are using a format file. You will need to change the terminator for the last field to be \n only.</s>
<s>[INST]Add AG replica "the edition of this SQL Server instance is different from the edition of the instance hosting the primary replica"" I am creating availability groups, I have three nodes in the cluster (one node in Azure, two on prem). Added the on prem node without any issues, when adding the azure node as a replica its throwing an error "the edition of this SQL Server instance is different from the edition of the instance hosting the primary replica" confirmed all SQL instances on 13. 0.5850.14. Anyone came across this issue?[/INST]I have not seen this error message before, but if I did I would try to read it. My next step would be to run "SELECT @@version" on all three nodes and see what the mismatch may be.</s>
<s>[INST]error incorrect syntax near '/A' when make dynamic query ? I work on SQL server 2012 i face issue error incorrect syntax near '/A' Msg 102, Level 15, State 1, Line 4 Incorrect syntax near '/A'. so How to solve this issue please ? create table #Allfeatures ( ZPLID INT, ZFeatureKey nvarchar(20), IsNumericValue int ) insert into #Allfeatures(ZPLID,ZFeatureKey,IsNumericValue) values (75533,'1505730036',0) create table #Condition ( Code nvarchar(20), ZFeatureKey nvarchar(20), ZfeatureType nvarchar(20), EStrat nvarchar(20), EEnd NVARCHAR(10) ) insert into #Condition (Code,ZFeatureKey,ZfeatureType,EStrat,EEnd) values ('8535400000','1505730036',NULL,'>1000',' '), ('8535400000','1505730036',NULL,'>280AV',' '), ('8535400000','1505730036',NULL,'N/A',' '), ('8535400000','1505730036',NULL,NULL,' ') CREATE TABLE #PartAttributes ( PartID INT, ZFeaturekEY NVARCHAR(20), AcceptedValuesOption_Value INT, Name nvarchar(20) ) insert into #PartAttributes(PartID,ZFeaturekEY,AcceptedValuesOption_Value,Name) values (4977941,1505730036,280,'280VDC'), (4977936,1505730036,280,'280VDC'), (4977935,1505730036,280,'280VDC') DECLARE @Sql nvarchar(max) DECLARE @ConStr nvarchar(max) SET @ConStr= STUFF((SELECT CONCAT(' Or (PM.ZfeatureKey= ''', CC.ZfeatureKey , '''', IIF(CC.ZfeatureType='Qualifications',' And AcceptedValuesOption_Value ' , ' And Name ' ) , LEFT(EStrat, 1), '''', SUBSTRING(EStrat, 2, LEN(EStrat) -1), ''')') --ValueName FROM #Condition CC INNER JOIN #Allfeatures AL ON AL.ZfeatureKey = CC.ZfeatureKey AND AL.IsNumericValue =0 FOR XML PATH(''), TYPE).value('(./text())[1]','varchar(max)'),1,3,'') SET @Sql= CONCAT(' SELECT PartID,Code,Count(1) as ConCount FROM #PartAttributes PM INNER JOIN #Condition Co ON Co.ZfeatureKey = PM.ZfeatureKey ', 'Where (1=1 and ',@ConStr,' ) Group By PartID,Code ' , ' Having Count(1)>= ',(SELECT COUNT(1) FROM #Condition)) EXEC (@SQL) [/INST]create table #Allfeatures ( ZPLID INT, ZFeatureKey nvarchar(20), IsNumericValue int ) insert into #Allfeatures(ZPLID,ZFeatureKey,IsNumericValue) values(75533,'1505730036',0) create table #Condition ( Code nvarchar(20), ZFeatureKey nvarchar(20), ZfeatureType nvarchar(20), EStrat nvarchar(20), EEnd NVARCHAR(10) ) insert into #Condition (Code,ZFeatureKey,ZfeatureType,EStrat,EEnd) values ('8535400000','1505730036',NULL,'>1000',' '), ('8535400000','1505730036',NULL,'>280AV',' '), ('8535400000','1505730036',NULL,'N/A',' '), ('8535400000','1505730036',NULL,NULL,' ') CREATE TABLE #PartAttributes ( PartID INT, ZFeaturekEY NVARCHAR(20), AcceptedValuesOption_Value INT, Name nvarchar(20) ) insert into #PartAttributes(PartID,ZFeaturekEY,AcceptedValuesOption_Value,Name) values (4977941,1505730036,280,'280VDC'), (4977936,1505730036,280,'280VDC'), (4977935,1505730036,280,'280VDC') DECLARE @Sql nvarchar(max) DECLARE @ConStr nvarchar(max) SET @ConStr = STUFF((SELECT CONCAT(' Or (PM.ZfeatureKey= ''', CC.ZfeatureKey , '''', IIF(CC.ZfeatureType = 'Qualifications',' And AcceptedValuesOption_Value ', ' And Name '), CASE WHEN EStrat = 'N/A' THEN '=''N/A''' WHEN EStrat IS NULL THEN 'IS NULL' ELSE LEFT(EStrat, 1) + '''' + SUBSTRING(EStrat, 2, LEN(EStrat) -1) + '''' END, ')') --ValueName FROM #Condition CC INNER JOIN #Allfeatures AL ON AL.ZfeatureKey = CC.ZfeatureKey AND AL.IsNumericValue =0 FOR XML PATH(''), TYPE).value('(./text())[1]','varchar(max)'),1,3,'') SET @Sql= CONCAT(' SELECT PartID, Code, Count(1) as ConCount FROM #PartAttributes PM INNER JOIN #Condition Co ON Co.ZfeatureKey = PM.ZfeatureKey ', 'Where 1=1 and (', @ConStr, ' ) Group By PartID,Code ' , ' Having Count(1)> = ',(SELECT COUNT(1) FROM #Condition))</s>
<s>[INST]issue Conversion failed when converting the nvarchar value '280VDC' to data type int why and how to solve I work on SQL server 2012 I Face issue display for me as Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the nvarchar value '280VDC' to data type int. How to solve this issue please my script as below create table #Allfeatures ( ZPLID INT, ZFeatureKey nvarchar(20), IsNumericValue int ) insert into #Allfeatures(ZPLID,ZFeatureKey,IsNumericValue) values (75533,'1505730036',0) create table #Condition ( Code nvarchar(20), ZFeatureKey nvarchar(20), ZfeatureType nvarchar(20), EStrat nvarchar(20), EEnd NVARCHAR(10) ) insert into #Condition (Code,ZFeatureKey,ZfeatureType,EStrat,EEnd) values ('8535400000','1505730036',NULL,'>1000',' ') CREATE TABLE #PartAttributes ( PartID INT, ZFeaturekEY NVARCHAR(20), AcceptedValuesOption_Value INT, Name nvarchar(20) ) insert into #PartAttributes(PartID,ZFeaturekEY,AcceptedValuesOption_Value,Name) values (4977941,1505730036,280,'280VDC'), (4977936,1505730036,280,'280VDC'), (4977935,1505730036,280,'280VDC') DECLARE @Sql nvarchar(max) DECLARE @ConStr nvarchar(max) SET @ConStr= STUFF((SELECT CONCAT(' Or (PM.ZfeatureKey= ', CC.ZfeatureKey , IIF(CC.ZfeatureType='Qualifications',' And AcceptedValuesOption_Value ' , ' And Name ' ) , CAST(EStrat AS NVARCHAR(2500)),')') --ValueName FROM #Condition CC INNER JOIN #Allfeatures AL ON AL.ZfeatureKey = CC.ZfeatureKey AND AL.IsNumericValue =0 FOR XML PATH(''), TYPE).value('(./text())[1]','varchar(max)'),1,3,'') SET @Sql= CONCAT(' SELECT PartID,Code,Count(1) as ConCount FROM #PartAttributes PM INNER JOIN #Condition Co ON Co.ZfeatureKey = PM.ZfeatureKey ', 'Where (1=1 and ',@ConStr,' ) Group By PartID,Code ' , ' Having Count(1)>= ',(SELECT COUNT(1) FROM #Condition)) EXEC (@SQL) [/INST]I think the problem is the value '>1000' for the column EStrat. Since data type of the column Name is nvarchar(20), you cannot use Name > 1000. Try this: SET @ConStr= STUFF((SELECT CONCAT(' Or (PM.ZfeatureKey= ''', CC.ZfeatureKey , '''', IIF(CC.ZfeatureType='Qualifications',' And AcceptedValuesOption_Value ' , ' And Name ' ) , LEFT(EStrat, 1), '''', SUBSTRING(EStrat, 2, LEN(EStrat) -1), ''')') --ValueName FROM #Condition CC INNER JOIN #Allfeatures AL ON AL.ZfeatureKey = CC.ZfeatureKey AND AL.IsNumericValue =0 FOR XML PATH(''), TYPE).value('(./text())[1]','varchar(max)'),1,3,'')</s>
<s>[INST]Split one String into Multiple Columns - SQL Hi Developers hope all is well i just want to understand something i have one column that has a string length Example of the data set below Data Set If I take this route ill get there quicker Now what i need to do is take that string and split it into three columns, however it needs to be split into those three columns based on 14 characters Output1 Output2 Output3 is this achievable, i need to understand how is this possible[/INST]To take 14 characters, check a sample: declare @tab as table (col varchar(max)) insert @tab values ('If I take this route ill get there quicker') select left(col, 14) as Output1, substring(col, 1+14, 14) as Output2, substring(col, 1+14+14, 14) as Output3 To divide into three parts: select left(col, len(col)/3) as Output1, substring(col, 1+len(col)/3, len(col)/3) as Output2, substring(col, 1+len(col)/3*2, len(col) - len(col)/3*2) as Output3</s>
<s>[INST]Configure a Windows Firewall for database port Hi, We are using SQL Server 2012, 2016 & 2017 in our production environment. We used default port 1433. Now we want to change the default port 1433 to any non-default port i.e 1455. Do we need to just change the port through SQL Server configuration manager or we need to Configure a Windows Firewall for database port through inbound and outbound rules also?[/INST]good question. Never checked it by myself. I'd think that the configuration manager does not take care of firewall settings if you change the ports. So you need to adjust the inbound rule. Regarding the outbound rule: those are always random high ports. Example: If I talk with my local SSMS to a SQL Server connected to port 1433 the communication port back to my client is always high range starting at 49xxx If you use a stateful firewall then you just need to take care about the inbound ports as far as I know.</s>
<s>[INST]Incorrect syntax Near 1000 when have number with comparison operators ? I work on Sql server 2012 I face issue When extract Numbers with comparison operator give me error incorrect syntax Near 1000 because I get number but cannot also get comparison operator with it . I need to get (> numbers or \<numbers or \>=number or \<= number) this is sample for test create table #Allfeatures ( ZPLID INT, ZFeatureKey nvarchar(20), IsNumericValue int ) insert into #Allfeatures(ZPLID,ZFeatureKey,IsNumericValue) values(75533,'1505730036',0) create table #Condition ( Code nvarchar(20), ZFeatureKey nvarchar(20), ZfeatureType nvarchar(20), EStrat nvarchar(20), EEnd NVARCHAR(10) ) insert into #Condition (Code,ZFeatureKey,ZfeatureType,EStrat,EEnd) values ('8535400000','1505730036',NULL,'>1000',' '), ('8535400000','1505730036',NULL,'>280AV',' '), ('8535400000','1505730036',NULL,'N/A',' '), ('8535400000','1505730036',NULL,NULL,' ') CREATE TABLE #PartAttributes ( PartID INT, ZFeaturekEY NVARCHAR(20), AcceptedValuesOption_Value INT, Name nvarchar(20) ) insert into #PartAttributes(PartID,ZFeaturekEY,AcceptedValuesOption_Value,Name) values (4977941,1505730036,280,'280VDC'), (4977936,1505730036,280,'280VDC'), (4977935,1505730036,280,'280VDC') DECLARE @Sql nvarchar(max) DECLARE @ConStr nvarchar(max) SET @ConStr= STUFF((SELECT CONCAT(' Or (PM.ZfeatureKey= ', CC.ZfeatureKey , IIF(CC.ZfeatureType='Qualifications',' And AcceptedValuesOption_Value ' , ' And Name ' ) , CAST( cast(LEFT(SUBSTRING(EStrat, PATINDEX('%[0-9.-]%', EStrat), 2500), PATINDEX('%[^0-9.-]%', SUBSTRING(EStrat, PATINDEX('%[0-9.-]%', EStrat), 2500) + 'X') -1) as float) --EStrat AS NVARCHAR(2500)) ,')') FROM #Condition CC INNER JOIN #Allfeatures AL ON AL.ZfeatureKey = CC.ZfeatureKey AND AL.IsNumericValue =0 FOR XML PATH(''), TYPE).value('(./text())[1]','varchar(max)'),1,3,'') ---------------- SET @Sql= CONCAT(' SELECT PartID, Code, Count(1) as ConCount FROM #PartAttributes PM INNER JOIN #Condition Co ON Co.ZfeatureKey = PM.ZfeatureKey ', 'Where 1=1 and (', @ConStr, ' ) Group By PartID,Code ' , ' Having Count(1)> = ',(SELECT COUNT(1) FROM #Condition)) EXEC (@SQL) I need to modify pattern \[0-9\] to get also comparison operators as > numbers or \<numbers or \>=number or \<= number [/INST]only one thing wrong > \> 280 > must be > =280 According to your script, “>1000” and “>280” are based on information from #Condition table. If you want to support “=” too, then replace “>280AV” with “=280AV” in #Condition table and adjust the script: SET @ConStr= STUFF((SELECT CONCAT(' Or (PM.ZfeatureKey= ', CC.ZfeatureKey , IIF(CC.ZfeatureType='Qualifications',' And AcceptedValuesOption_Value ' , ' And translate(Name, ''VDCA'', space(4)) ' ) , CAST( cast(LEFT(SUBSTRING(EStrat, PATINDEX('%[<>=0-9.-]%', EStrat), 2500), PATINDEX('%[^<>=0-9.-]%', SUBSTRING(EStrat, PATINDEX('%[<>=0-9.-]%', EStrat), 2500) + 'X') -1) as nvarchar(2500)) --EStrat AS NVARCHAR(2500)) ,')') FROM #Condition CC INNER JOIN #Allfeatures AL ON AL.ZfeatureKey = CC.ZfeatureKey AND AL.IsNumericValue =0 where EStrat <> 'N/A' FOR XML PATH(''), TYPE).value('(./text())[1]','varchar(max)'),1,3,'')</s>
<s>[INST]Export from SQL Server to Excel, all text fields have a leading single quote Using SQL Server 2019 I'm exporting data from a table to Excel, however, ALL cells with data have a leading single quote. The corrupts all the data. How can this be avoided? Thank you.[/INST]I have not used the Export wizard to get data to Excel, so I can't speak to that. When I export data to Excel, I do one of these: 1. Run a query in SSMS and copy paste into Excel. This works for simple stuff, but since Excel guesses the data type and outsmarts itself, this can fail. For instance, if there are strings like 00110011, Excel thinks it's a number, and you lose the zeroes. 2. In Excel, go to the Data menu. Select New Query, second item from the left. Here select From Database and then from SQL Server. In the form you get, select Advanced options. This will permit you to run a query. There is an menu item Get External Data in Excel that also seems to support from SQL Server, but I have not worked with that one. By the way, I would expect those single quotes are there to prevent Excel from interpreting the data in its own way. That is, you want to enter `00110011` in a cell manually, you need to enter `'00110011` for Excel to obey.</s>
<s>[INST]SSMS import wizard using CSV file with full date is not loading milliseconds to SQL Server table I have some large CSV files that I'm trying to import into a SQL Server table using ssms import wizard. One of the columns is a date column formatted as yyyy-mm-dd hh:MM:ss:xxx. I've tried every date format in the source field that is offered to me, but it, at best, gives me the entire date with the milliseconds as .000 rather than the value that is in the .txt CSV file. The only thing I can think of is that the input date has the milliseconds after a colon (:) rather that a period (.). I could write a program that converts the colon to a period and then load it, but I did edit the file and changed the first six rows to period and that didn't seem to have any effect. For the import I'm using "Flat File Source", under "Advanced", I select "DataType" for the column and have used every one of the following as the DataType. database date [DT_DBDATE], database time [DT_DBTIME], database time with precision [DT_DBTIME2], database timestamp [DT_DBTIMESTAMP], database timestamp with precision [DT_DBTIMESTAMP2], DT_DBTIMESTAMPOFFSET] and even date [DT_DATE], decimal [DT_DECIMAL], file timestamp [DT_FILETIME] The Destination is to SQL Server Native Client 11.0 to destination Type of datetime2 which is defined on the table as datetime2(7), not null. With all these attempts I either get a "data would be truncated" error, or it would load with the milliseconds set to 000 rather than the value that is in the CSV file. I would appreciate any help. Thanks, Bob[/INST]You will be much happier if you pull all fields from the CSV as strings, and use derived columns to convert the string to the target data type.</s>
<s>[INST]What to buy for 40 v-core enviroment? My Client have to but SQL 2019 license. Virtual machine is built from 4 X CPU's with 10 physical cores each, so 40 physical cores together. EULA, as I understand suggest to count it as v-cores equal with threads in CPU's. For me it is 80 v-cores, co 40 x 2 core licenses of Standard. Do I think correct? Another question is, that Standard SQL works with 24 core maximum. Does it mean, that Client have to buy Enterprise for this 80 v-cores?[/INST]Does it mean, that Client have to buy Enterprise for this 80 v-cores? If you have enterprise edition installed on VM which has 80 cores (including hyper threading) you need to license all the cores. This is what MS licensing says for Virtual machines. For physical you would have to license "physical cores" though. > Standard SQL works with 24 core maximum. For standard edition MS says lesser of four sockets or 24 virtual cores. So which ever is lesser will be counted, rest cores will be ignored in standard edition</s>
<s>[INST]Drop or keep less frequently used indexes In a database, there many indexes created for most of the tables. some indexes are highly frequently used while some are used once in a month. Due to many indexes the insert is very slow. But the indexes are used once every month by monthly report queries. So do I drop or keep the indexes? What is the solution to this situation?[/INST]There's no "solution" to this. Only your prioritization. Do you prioritize the reports or the inserts? You can of course disable the indexes and rebuild then before the reports, but chances are that the rebuild takes longer time than running the reports without the indexes.</s>
<s>[INST]Why wont my log backups shrink the log file? Hi, I have a database with a half a terrabyte log file. It says the log is 96% full. It wont shrink and I cant put it in simple mode because it is involved in replication. I take log backups every 2 minutes. I have done a full backup and the log still wont shrink.. I thought the log should empty after a transaction log backup... is this not the case? [/INST]take log backups every 2 minutes. I have done a full backup and the log still wont shrink.. This is because your replication might not be working properly. What is output of `select log_reuse_wait_desc from sys.databases where name=''db_name` My hunch, replication. Is your log reader agent not working, I am sure you have some issue with replication and since you say your have 500GB log file I would say fixing replication and moving those 500GB log on subscriber would not be good idea altogether as it would take time. But you are the best judge. My saying is you might need to reinitialize the replication > I thought the log should empty after a transaction log backup... is this not the case? Transaction log backup would mark transaction log blocks as reusable ONLY IF no other process needs that lock or is holing the lock. The process can be log backup, replication, Availability groups etc.</s>
<s>[INST]How do I pass as a parameter a column name while performing SELECT SUM? Hello everyone, can not get this working, there are no any exceptions, however this code returns "0". When I put a real column name (e.g. Quantity) instead of @ColumnName, this returns correct sum. I checked in Debug, the property ColumnName gets true column name. So my question is, what I'm doing wrong? cmd.CommandText = "SELECT SUM(@ColumnName) FROM Components WHERE Date BETWEEN @Date1 AND @Date2 "; cmd.Parameters.AddWithValue("@ColumnName", ColumnName); cmd.Parameters.AddWithValue("@Date1", Time1); cmd.Parameters.AddWithValue("@Date2", Time2); Thanks. [/INST]Try something like this: cmd.CommandText = "SELECT SUM([" + ColumnName.Replace("]", "]]") + "]) FROM Components WHERE Date BETWEEN @Date1 AND @Date2 ";</s>
<s>[INST]How to get Total Count of table in column in sql server 2016 i am trying to get count of rows in tables with below code. SELECT count (*) from Resistortable SELECT count (*) from capacitortable Is there any way to get result like below. Resistortable|capacitortable 200 | 545 The output in single row with table name. Please help. [/INST]SELECT (SELECT count (*) from Resistortable) AS RestistorTable, (SELECT count (*) from capacitortable) AS capacitortable</s>
<s>[INST]How to Insert Book details using While Loop where status is not null? I work on SQL SERVER 2012 . I face issue I can't use While loop to insert Books details that status is not NULL to table #BookHaveGeneralStatus . Meaning if any book have only one status not null on Books Details then insert it on table #BookHaveGeneralStatus using While loop . but if all Status is Null per Book Id for all rows on BookDetails Table then Not insert it on #BookHaveGeneralStatus . create table #mainbooks ( BookId int, BookName nvarchar(50) ) insert into #mainbooks values (1,'McGrawHill'), (2,'Visio'), (3,'Press'), (4,'ForDummies'), (5,'LearningIn21hours'), (6,'Udemy') ----DROP TABLE #BookDetails create table #BookDetails ( BookdetailsId int, BookId int, PublishersPlaces nvarchar(50), Status nvarchar(50) ) ----select * from #BookDetails insert into #BookDetails values (94,1,'Cairo Jordan',NULL), (95,1,'tahrir sequare',NULL), (96,1,'ramsis sequare',NULL), (97,2,'Cairo Jordan',NULL), (98,2,'tahrir sequare',NULL), (99,2,'ramsis sequare',NULL), (100,3,'Cairo Jordan','Inshelf'), (101,3,'tahrir sequare','NULL'), (102,3,'ramsis sequare',NULL), (103,4,'Cairo Jordan','Inshelf'), (104,4,'tahrir sequare','Inprogress'), (105,4,'ramsis sequare','publish'), (106,5,'Cairo Jordan','Inshelf'), (107,5,'tahrir sequare','Inprogress'), (108,5,'ramsis sequare','publish'), (109,6,'Cairo Jordan','Inshelf'), (110,6,'tahrir sequare','Inprogress'), (111,6,'ramsis sequare','publish') create table #BookHaveGeneralStatus ( BookgeneralId int, BookId int, PublishersPlaces nvarchar(50), Status nvarchar(50) ) so that bookid 1 and 2 will not inserted and book id 3,4,5,6 will inserted so How to do that please using while loop ? while loop insert into table #BookHaveGeneralStatus values will be all data on table #BookDetails that have all status not null or at least one not null Book id 3 will added because it have at least on status not null expected result must added by while loop from #BookDetails to #BookHaveGeneralStatus BookdetailsId BookId PublishersPlaces Status 100 3 Cairo Jordan Inshelf 101 3 tahrir sequare NULL 102 3 ramsis sequare NULL 103 4 Cairo Jordan Inshelf 104 4 tahrir sequare Inprogress 105 4 ramsis sequare publish 106 5 Cairo Jordan Inshelf 107 5 tahrir sequare Inprogress 108 5 ramsis sequare publish 109 6 Cairo Jordan Inshelf 110 6 tahrir sequare Inprogress 111 6 ramsis sequare publish [/INST]If you need a *WHILE* loop for some reasons, then also consider a cursor. For example: declare c cursor for select d.BookdetailsId, d.BookId, d.PublishersPlaces, d.[Status] from #BookDetails d inner join #mainbooks b on b.BookId = d.BookId where d.BookId in ( select BookId from #BookDetails where [Status] is not null open c while 0=0 begin declare @bookDetailsId int declare @Id int declare @publisherPlaces nvarchar(50) declare @status nvarchar(50) fetch next from c into @bookDetailsId, @Id, @publisherPlaces, @status if @@FETCH_STATUS <> 0 break insert #BookHaveGeneralStatus select @bookDetailsId, @Id, @publisherPlaces, @status end close c deallocate c select * from #BookHaveGeneralStatus order by BookgeneralId An *INSERT* without loop: insert #BookHaveGeneralStatus select d.BookdetailsId, d.BookId, d.PublishersPlaces, d.[Status] from #BookDetails d inner join #mainbooks b on b.BookId = d.BookId where d.BookId in ( select BookId from #BookDetails where [Status] is not null</s>
<s>[INST]Restoring Datawarehouse DB from one SQL Server to DEV & UAT on a different SQL Server Currently in our Production server there is a webservice call being made. The call works fine on PROD, but not in UAT and DEV. This is due to inconsistencies in the third party managed database. Every month, there is a excel spreadsheet we have to grab from an external source (website) that will update old records or insert new records to SQL Server. Apparently they are already uploading the information from the excel sheet to the data warehouse on a schedule, so we could potentially be ingesting it directly from DW instead of needing to manually process a spreadsheet. However, when I checked the data inside the tables, they are repeated and inconsistent. So from my understanding, it sounds like I can backup the DB and restore it on to DEV and UAT. My questions: 1. Before starting the restore process, what are some considerations I need to discuss with my team members? 2. What is the process of cleaning up the data? 3. How to automate process monthly? [/INST]My thoughts on your questions based on what you have said: 1. Before starting the restore process, what are some considerations I need to discuss with my team members?. Answers - How current does the data need to be? This will determine how often to perform the restore. The user of the data should be able to tell you this. 2. What is the process of cleaning up the data? Answer - This depends on what the data is being used for. What data is not needed (age?) You could write a cleanup script to purge data from the table based on some kind of timestamp. The application owner and/or users can tell you this. 3. How to automate process monthly? Answer - There are a different ways of automating a database restore to another Sql Server. One way would be to script/schedule it in a Sql agent job.</s>
<s>[INST]Script Generator via SMO and C# Hi I would like to produce SQL Data Script via SMO with C# 1. I am trying first to generate data script with one table. And i need to produce only insert script with a few rows only of a table , not all table data. How add filter ? like a primary key id or something ? 2. My code is very slow when try to execute scripter.EnumScript , why ? how can make it better ? My code : public string GenerateSqlScript(bool includeData) { Server server = new Server(@"" + DBMain.ConnDetails.Server); Database database = server.Databases[DBMain.ConnDetails.Catalog]; List<Urn> list = new List<Urn>(); DataTable dataTable = database.EnumObjects(DatabaseObjectTypes.Table); List<Table> tableList = new List<Table>(); foreach (DataRow row in dataTable.Rows) { if(row.ItemArray[2].ToString()== "myTable") list.Add(new Urn((string)row["Urn"])); //MessageBox.Show(row.ItemArray[2].ToString()); } Scripter scripter = new Scripter(); scripter.Server = server; scripter.Options.IncludeDatabaseContext = false; scripter.Options.IncludeHeaders = true; scripter.Options.SchemaQualify = true; scripter.Options.ScriptData = includeData; scripter.Options.SchemaQualifyForeignKeysReferences = true; scripter.Options.NoCollation = true; scripter.Options.DriAllConstraints = true; scripter.Options.DriAll = true; scripter.Options.DriAllKeys = true; scripter.Options.Triggers = true; scripter.Options.DriIndexes = true; scripter.Options.ClusteredIndexes = true; scripter.Options.NonClusteredIndexes = true; scripter.Options.ToFileOnly = false; //this is very slow... var scripts = scripter.EnumScript(list.ToArray()); string result = ""; foreach (var script in scripts) result += script + Environment.NewLine; return result; } [/INST]with a few rows only of a table , not all table data. How add filter ? There is no option to add a filter, the data script generator create INSERTS for all data in the table. If you want to limit it, create a view with all columns and a filter on the data.</s>
<s>[INST]SQL Agent job by non-admin : Linked servers cannot be used under impersonation without a mapping for the impersonated login On SQL 2014 all users can run queries in SSMS using linked servers without issue. However since they are not sysadmins, their SQL Agent job fails with: “Linked servers cannot be used under impersonation without a mapping for the impersonated login” Linked server is configured for “Be made using the login’s current security context”. I tried adding in linked Server Security tab, Local server login to remote server login mappings, the AD account of the of the Local Login and checked “impersonate”, but still does not work. I can reproduce in SSMS by running execute as login before the linked server query since linked server generates an "execute as login" as i understood behind the scenes. I do not want to use SQL auth for the remote User, but just the local AD account impersonate for the remote user, basically same as running SSMS query. What is the solution, and am I missing anything on the AD side? Thanks,[/INST]1. Correct, you must absolutely never agree to let sysadmin run jobs which executes code which can be modified by non-sysadmin users. 2. Well, it is not impersonation. It is a login. The user you set for the proxy should not be an account for a real user. Technically it could be, but since you need to store the password for the proxy account in SQL Server, it is obviously not a very good idea. 3. Yes, these are your options. If you let them into Agent, you need to work with proxies. Or you keep them out entirely, and the users will need solve the problem on their own with Task Scheduler, or a user-written service..</s>
<s>[INST]Always encrypted and triggers We are planning for encrypting columns in a table that has trigger for INSERT and UPDATE. When I try to encrypt a few of the columns I get an error shown below. I think I understand it because the trigger is not on the client side but I don't know how to work around this. Warning SQL72038: The object [David] already exists in database with a different definition and will not be altered. Error SQL72014: .Net SqlClient Data Provider: Msg 206, Level 16, State 2, Procedure trgPatientsAudit, Line 23 Operand type clash: nvarchar(20) encrypted with (encryption_type = 'DETERMINISTIC', encryption_algorithm_name = 'AEAD_AES_256_CBC_HMAC_SHA_256', column_encryption_key_name = 'CEK_Auto1', column_encryption_key_database_name = 'kdctest') is incompatible with nvarchar Error SQL72045: Script execution error. The executed script: CREATE TRIGGER [dbo].[trgPatientsAudit] ON [dbo].[tblPatients] AFTER INSERT, UPDATE AS BEGIN SET NOCOUNT ON; DECLARE @idnumber AS INT; SELECT @idnumber = CONVERT (INT, session_context(N'USERID')); IF EXISTS (SELECT * FROM DELETED) BEGIN INSERT INTO [dbo].[tblPatientsAudit] ([PatientID], [FirstName], [MiddleName], [LastName], [DOB], [StatusID], [DietID], [StartDiet], [EndDiet], [Email], [OrgID], [Gender], [MedRecordNo], [UserLoginID], [LastUpdated]) SELECT i.[PatientID], i.[FirstName], i.[MiddleName], i.[LastName], i.[DOB], i.[StatusID], i.[DietID], i.[StartDiet], i.[EndDiet], i.[Email], i.[OrgID], Error SQL72014: .Net SqlClient Data Provider: Msg 206, Level 16, State 2, Procedure trgPatientsAudit, Line 61 Operand type clash: nvarchar(20) encrypted with (encryption_type = 'DETERMINISTIC', encryption_algorithm_name = 'AEAD_AES_256_CBC_HMAC_SHA_256', column_encryption_key_name = 'CEK_Auto1', column_encryption_key_database_name = 'kdctest') is incompatible with nvarchar Error SQL72045: Script execution error. The executed script: CREATE TRIGGER [dbo].[trgPatientsAudit] ON [dbo].[tblPatients] AFTER INSERT, UPDATE AS BEGIN SET NOCOUNT ON; DECLARE @idnumber AS INT; SELECT @idnumber = CONVERT (INT, session_context(N'USERID')); IF EXISTS (SELECT * FROM DELETED) BEGIN INSERT INTO [dbo].[tblPatientsAudit] ([PatientID], [FirstName], [MiddleName], [LastName], [DOB], [StatusID], [DietID], [StartDiet], [EndDiet], [Email], [OrgID], [Gender], [MedRecordNo], [UserLoginID], [LastUpdated]) SELECT i.[PatientID], i.[FirstName], i.[MiddleName], i.[LastName], i.[DOB], i.[StatusID], i.[DietID], i.[StartDiet], i.[EndDiet], i.[Email], i.[OrgID], '. [/INST]The target columns in the audit table must be encrypted the same way. That is with the same key, the same encryption type etc. Whether that will actually will work out, I don't know, as I haven't tested. But that's the only chance that it can work.</s>
<s>[INST]sql 2008 decommission - Database oddity HI all Getting rid of my final SQL 2008 Instance, 25 old DB's I'm moving to sql 2017, making sure they are accessible and in Compatibility 100 mode, then backing them up from SQL 2017 and then archiving the backup files away. One of those Databases, I cannot find an owner for it, it doesn't appear to have any access to it of late (Been using the "sp_who" stored procedure on and off for 2 weeks), but it has a very strange mdf and ldf size difference. - DB mdf file is 1344KB in size (1MB) - DB ldf file is 146, 992, 567 kb in size (146GB!) I'm comfortable the DB is legacy....but... **Normally I would just toggle from FULL into SIMPLE recovery and that's that.....but I'm a little more weary of doing so just based on HOW this size differential could come about. Any thoughts on what could cause that, alternative approach I should take?** I dont have 146GB space on this server to backup the transaction log you see and then proceed from there. Coop [/INST]So if they never performed a full backup, which considering there is 146gb of “data” in the log file is very odd, but if no full backup performed then would data never have been committed? They indeed performed a full backup without full backup a log chain cannot start. Since your log file is massive atleast one full backup was definitely taken. > If never committed, then I’m guessing a complete automatic rollback was always possible....? SQL Server runs program in auto commit mode. Unless the program gets killed, or is rolled back by SQL Server or external causes it will not rollback. What would have happened is some big DML would have run and before finishing someone cancelled it to rollback. SQL Server log file would have information about the DML changes and the rollback changes. This can make log file big. Also note log file `do not have actual data but information about the changes made to the data`. > and also, I notice that this database has been set to “single user mode” at some stage. None of the other dbs were, but this one yes. Someone would have done that either for testing or for some other purpose. What is output of `select log_reuse_wait_desc from sys.databases where name='db_name'` replace db_name with database name. This will tell us what is stopping the log from getting truncated.</s>
<s>[INST]Log file size is bigger than the datafile size One of the database has datafile size 6.5 GB and Transactional Log 21 GB. What should be the process of reducing the log file size? Backup job is enabled in Transactional and Full backup on 2016 server.[/INST]Just to be clear. The log file NEVER gets physically smaller, unless you manually shrink it. A log backup set the data inside as "logically" available for reuse. It does NOT physically make the file smaller. The log file is that big, because at some point is was required to be that size.</s>
<s>[INST]Execute a single stored procedure using parallelism Hello Experts, I am working on a SQL server 2019 environment with Maxdop set to 8 and Cost threshold at default 5. Application executes a stored procedure SP1 on a Database called DB1. Maxdop for DB1 at database level is 1. Sp1 execution takes close to 90 seconds. But when I change Maxdop value to 8 at database level, the same store procedure completes in 2 seconds. But the problem is I will not be able to change the Maxdop from 1 to 8 at database level. I tried adding a maxdop hint within the stored proc, but it never goes parallel as Maxdop is 1 at db level. I would like your advise to see if I can execute the stored proc using parallelism without changing Maxdop value at DB level to something else from 1. Thanks; Zulu[/INST]But the problem is I will not be able to change the Maxdop from 1 to 8 at database level. I tried adding a maxdop hint within the stored proc, but it never goes parallel as Maxdop is 1 at db level. Books Online says: > Query hints can still override the database scoped MAXDOP in order to tune specific queries that need different setting. So there is more to it. Anyway, if execution time goes from 90 seconds to 2 seconds, it is not only a matter of using seven more cores, but there other changes in the plan as well. So I would suggest that you study the parallell execution plan and compare with serial. Are different indexes being used? Maybe you need to add better indexes. Maybe the query needs tweaking.</s>
<s>[INST]Display Numbers as below style in sql server I need small help regarding sql statement: In Sql server: The value as 1500 Then number should be display as 2 different options like: For Example: Then need to return data set as 1-1000 1001-1500 That Means Here i am splitting 2nd option after 1000,so finally i need dynamically if i give any value. Here i don't need any between numbers One more Example: If value=3699 Then need to return data set as 1-1000 1001-2000 2001-3000 3001-3699 [/INST]It is not difficult to generate such intervals using recursive query: declare @number int = 3699 ; with E as ( select 0 as [start], 0 as [end] union all select [end] + 1, iif(@number <= [end] + 1000, @number, [end] + 1000) from E where [end] + 1 <= @number ) select * from E where [start] > 0 order by [start] option (maxrecursion 0) It depends on how do you want to use these numbers.</s>
<s>[INST]How to prevent update to category only by part id when it be blank or NULL on inputdata table ? I work on sql server 2012 I face issue I need to do update data found on table #DataUpdated based on part id exist on table #inputdata . my issue on category on inputdata will update #dataupdated table when it have value only and not equal NULL OR Blank . so I need to update full row by parts id . my issue i can't avoid update to data inputdata by partid where category on input data is null or blank so how to do that update d set d.category=i.category from #DataUpdated d inner join #inputdata i on i.partid=d.partid create table #inputdata ( PartId int, category nvarchar(50), NameGeneration nvarchar(50) ) insert into #inputdata(PartId,category,NameGeneration) values (2020,NULL,'v5070'), (2030, '','v5080'), (2050,'Iron2','v5090'), (2090,'Plaster2','v8000') create table #DataUpdated ( PartId int, category nvarchar(50), NameGeneration nvarchar(50) ) insert into #DataUpdated(PartId,category,NameGeneration) values (2020,'Plastic','v5050'), (2030,'Alomental','v5050'), (2050,'Iron','v5050'), (2090,'Plaster','v9000') result expected SELECT \* FROM #DataUpdated PartId category NameGeneration 2020 Plastic v5070 2030 Alomental v5080 2050 Iron2 v5090 2090 Plaster2 v8000 [/INST]This variation seems to work too: update u set u.category = isnull(nullif(i.category, ''), u.category), -- or: u.category = iif(i.category <> '', i.category, u.category), u.NameGeneration = i.NameGeneration from #inputdata i inner join #DataUpdated u on u.PartId=i.PartId</s>
<s>[INST]Incorrect Syntax Error In stored Procedure sql server 2016 Hi, The Stored Procedure is looks as: CREATE PROCEDURE Test_Res @COMPID int = '93', @DefaultorMissingvalue varchar(max) = NULL, @Startdate VARCHAR(50), @Enddate VARCHAR(50), @ICLAS_to_include varchar(max), @IID VARCHAR(10) AS BEGIN SET NOCOUNT ON; DROP TABLE IF EXISTS #Item SELECT ITEM INTO #Item FROM ( SELECT DISTINCT IPROD AS ITEM FROM TABLEA WHERE ICLAS in (select value from string_split(@ICLAS_to_include, ',' )) AND IID = @IID )R SELECT * FROM #Item END and when i tried to execute like : EXEC Test_Res @COMPID = '93', @DefaultorMissingvalue = NULL, @Startdate = '20200501' , @Enddate = '20200810', @ICLAS_to_include = ('01','02','03','04','13','14'), @IID 'USA' **but unfortunately i am getting error as Msg 102, Level 15, State 1, Line 6 Incorrect syntax near '('.** **The error i am getting at @ICLAS_to_include = ('01','02','03','04','13','14'),** Please help me, not sure where i am doing wrong. Many Thanks[/INST]Try this modification: @ICLAS_to_include = '01,02,03,04,13,14', If *ICLAS* column is a number, then:</s>
<s>[INST]Dynamic sql error in Select when empty string pass in sql server 2016 I am very new to dynamic sql. SQL SERVER 2016 The below code is written using dynamic sql, unfortunately throwing error. please help. CREATE PROCEDURE [USA_PHILIPS].[usp_stock] @VCM int, @ID varchar(25), --Always define your varchar lengths @SCHEMA_NAME sysname --Correct data type for object names AS BEGIN SET NOCOUNT ON; DECLARE @SQL nvarchar(MAX), @CRLF nchar(2) = NCHAR(13) + NCHAR(10) SET @SQL = N'DROP TABLE IF EXISTS ' + QUOTENAME(@SCHEMA_NAME) + N'.[stock];' + @CRLF + @CRLF + N'SELECT STOCKNUMBER,STOCKBOOKS,'No' as ISCHANGEMANAGEMENTACTIVATED, 0 as PERSONANNIVERSARYDAY, '' as NEWCOL,'Normal' as DEFAULTCASHDISCOUNTUSAGE',CASE WHEN VENDOR=23490 then '30-INTERCO' END AS VENDID + @CRLF + N'INTO ' + QUOTEMANE(@SCHEMA_NAME) + N'.[stock]' + @CRLF + N'FROM [USA_PHILIPS].[DMARTSTOCK]' + @CRLF + N'WHERE VCM=@VCM' + @CRLF + N' AND ID = @ID;'; EXEC sys.sp_executesql @SQL, N'@VCM int, @ID varchar(25)', @VCM, @ID; END; Not sure, I am getting error in select statement. [/INST]Try this fix: SET @SQL = N'DROP TABLE IF EXISTS ' + QUOTENAME(@SCHEMA_NAME) + N'.[stock];' + @CRLF + @CRLF + N'SELECT STOCKNUMBER,STOCKBOOKS,''No'' as ISCHANGEMANAGEMENTACTIVATED, 0 as PERSONANNIVERSARYDAY, '''' as NEWCOL,''Normal'' as DEFAULTCASHDISCOUNTUSAGE, CASE WHEN VENDOR=23490 then ''30-INTERCO'' END AS VENDID' + @CRLF + N'INTO ' + QUOTENAME(@SCHEMA_NAME) + N'.[stock]' + @CRLF + N'FROM [USA_PHILIPS].[DMARTSTOCK]' + @CRLF + N'WHERE VCM=@VCM' + @CRLF + N' AND ID = @ID;';</s>
<s>[INST]SQL Server 2019 - Scheduled jobs Bizarre incident - Next run date of all the jobs moved 6 months Forward by itself We are using SQL Server 2019 Enterprise Edition (Version 15.0.4073.23). Have about 100+ scheduled jobs which are hourly, daily, weekly or Monthly. Jobs stopped working today and on troubleshooting found that all the jobs are suddenly showing Next run date(Job activity Monitor) of some date in June 2021. No change has been made to the schedule of these jobs, and everything else looks normal. But the jobs won't run due to this issue. I have found a way to fix this by updating the schedule of the jobs. Once I do this Next run time is getting fixed I have been working with SQL server for about 15 years, and has not seen anything like this. Would like to know if anybody has faced similar issue or any idea what might be causing this. [/INST]This happens when the system clock date is set incorrectly when SQL Agent was started. Usually restarting the SQL Agent service will fix this problem. The next job start is recalculated when the agent service starts.</s>
<s>[INST]How to delete Max PartDetailsId for Reapeated parts Based on CompanyId and PartId ? I work on SQL server 2012 . I face issue I can't delete max PartDetailsId from part details based on part ID and company id that related to main table parts . if Part ID repeated on partdetails then I get max PartDetailsId by companyid and partid as Part ID 1222 and 1901 and delete max partsDetailsId from partdetails Table group by company id and partid. if Part ID not Repeated row then I will not delete it as Part ID 5000 create table #parts ( PartId int, PartNumber nvarchar(50) ) insert into #parts(PartId,PartNumber) values (1222,'x54310'), (1255,'m90110'), (1901,'f43398'), (5000,'gyzm30') create table #partsDetails ( partsDetailsId int, PartId int, CompanyId int ) insert into #partsDetails(partsDetailsId,partid,CompanyId) values (1225,1222,2020), (1500,1222,2020), (1600,1222,2020), (1650,1901,2030), (1700,1901,2030), (1750,5000,2707) so deleted PartDetailsId will be : partsDetailsId PartId CompanyId 1600 1222 2020 1700 1901 2030 [/INST]Since you are interested in *ROW_NUMBER*, then check one more possibility: ; with E as ( select row_number() over (partition by PartId, CompanyId order by partsDetailsId asc) as rna, row_number() over (partition by PartId, CompanyId order by partsDetailsId desc) as rnd from #partsDetails where PartId in (select PartId from #parts) ) delete from E where rnd = 1 and rna <> 1 It assumes that *partsDetailsId* are unique.</s>
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
103