text
stringlengths
209
10.7k
<s>[INST]Hi, I am trying to insert the value using INSERT INTO DimDestinationVAT (Warehouse_Code,Country_Code,VAT_Code,VAT_Value,Date_From,Date_To) VALUES ('MUSS', 'AT', '', '0', 2021-06-23,null ), ('MUSS', 'BE', '','0', 2021-06-23,null), ('MUSS', 'DK', '', '0', 2021-06-23,null), ('MUSS', 'FR', '', '0', 2021-06-23,null ), ('MUSS', 'DE', '', '0', 2021-06-23,null ), ('MUSS', 'IE', '', '0', 2021-06-23, null ), ('MUSS', 'IT', '', '0', 2021-06-23,null ), ('MUSS', 'NL', '', 0, 2021-06-23,null ), ('MUSS', 'ES', '', '0', 2021-06-23,null ), ('MUSS', '73', '', '0', 2021-06-23,null ) ; However it is erroring saying **Operand type clash: int is incompatible with date** I initially tried without specifying the column names as there is an auto increment field called id however that did not work. Table was created using create table DimDestinationVAT ( id int IDENTITY(1, 1) NOT NULL primary key, Warehouse_Code varchar(120), Country_Code varchar(120), VAT_Code varchar(120), VAT_Value numeric(18,0), Date_From date, Date_To date ) [/INST]Was missing the quotes on the date field.</s>
<s>[INST]What is the best practice set up for DB service account on Always On Cluster MS SQL 2019? Local or Domain service account?[/INST]microsoft.com/en-us/users/na/?userid=d25aefc1-239a-457c-af5a-46d8c9e858b1), It is generally recommended to use a domain account as the service account for the SQL Server Database Engine in an Always On Cluster. Using a domain account provides the following benefits: Centralized management: Domain accounts can be centrally managed by your organization's IT team, allowing for better control over password policies, authentication, and authorization. What is more, domain accounts can be used across multiple servers and can be easily reassigned to different servers if needed, providing flexibility in managing your SQL Server environment. Let's talk more about local accounts. Local accounts are limited to the local server and cannot be centrally managed by the IT team, resulting in increased complexity and difficulty in managing the account. Local accounts may have higher privileges on the local server, which can increase the risk of potential security breaches if the account is compromised. In addition, local accounts are bound to the specific server where they are created and cannot be easily reassigned to other servers.</s>
<s>[INST]I have two table: Parent table and child table. I have ETL Process which set 3 column EXCEPT INDIVIDUAL_ID as either NULL or empty string like '' on parent table based on the Individual_ID in child table. I am trying to create a stored procedure which tell if any of these 3 column have value other than NULL or '' for those Individual_ID mention in the child table. ``` DECLARE @Parent_Table TABLE ( individual_id BIGINT, race_code CHAR(10), age_code CHAR (20), gender_code CHAR (10) ) INSERT @Parent_Table SELECT 005,'DD4','DA2','' UNION ALL SELECT 009,'','','' SELECT 010,'','','M' DECLARE @CHILD_TABLE TABLE ( individual_id BIGINT ) SELECT 005 UNION ALL SELECT 009 UNION ALL SELECT 010 And output of SP looks OUTPUT LOOKS LIKE: individual_id, race_code, age_code, gender_code, REMARKS 005, DD4, DA2, '', VALUE PRESENT IN RACE_CODE AND AGE_CODE 009, '', '' , '', OK 010, '', D45A, '', VALUE PRESENT IN gender_code ``` Thanks a lot for help. Please help me how to do it in sql server 2019. [/INST]Try this: sql SELECT *, REMARKS = isnull('VALUR PRECENT IN ' + nullif(CASE WHEN len(race_code) > 0 THEN 'RACE_CODE ' ELSE '' END + CASE WHEN len(age_code) > 0 THEN 'AGE_CODE ' ELSE '' END + CASE WHEN len(gender_code) > 0 THEN 'GENDER_CODE ' ELSE '' END, ''), 'OK') FROM @Parent_Table</s>
<s>[INST]Hi , I have MSSQL transaction replication in place. Database "ABC" is published from server A to B into database "ABC". Its working fine. Now I want to replicate a table from server C database "ABC" to server B into database "ABC". Both publication database names are same & subscriber has also same name. Is it workable. Thanks[/INST]As long as the tables are different names, it is fine. The database name being the same has no relevance to replication.</s>
<s>[INST]Hi Team, how to generate script for all enabled agent jobs **(not all jobs)**. Thanks in advance[/INST]Have 150 jobs in Server1 and few are enabled & few are disabled. I want to migrate enabled jobs to Server2 from Server1.</s>
<s>[INST]Dear all, I'd like to get only one recurrence but it is returning more than one, obviously the condition is bad built, can you help me on the syntaxis? XML column (all the contents for a concrete row) ``` <Jobs> <Job JobName="Formulatrix Database Index Rebuilding.Subplan_1" JobEnabled="true" ScheduleName="Formulatrix Database Index Rebuilding.Subplan_1" ScheduleFrequency="Weekly" ScheduleInterval="Sat " ScheduleTime="01:00:00" ScheduleTimeDescription="Starting at 01:00:00" NextRunTime="2023-05-13 01:00:00" LastRunStatus="Successful" /> <Job JobName="Integrity_check_DBCC" JobEnabled="true" ScheduleName="monthly_integrity_check_schedule_wave2" ScheduleFrequency="Every 1 Months" ScheduleInterval="First Sat" ScheduleTime="20:00:00" ScheduleTimeDescription="Starting at 20:00:00" NextRunTime="2023-06-03 20:00:00" LastRunStatus="Successful" /> <Job JobName="syspolicy_purge_history" JobEnabled="true" ScheduleName="syspolicy_purge_history_schedule" ScheduleFrequency="Daily" ScheduleInterval="Every Day" ScheduleTime="02:00:00" ScheduleTimeDescription="Starting at 02:00:00" NextRunTime="2023-05-09 02:00:00" LastRunStatus="Successful" /> </Jobs> ``` It should return (only) : <Job JobName="Integrity_check_DBCC" JobEnabled="true" ScheduleName="monthly_integrity_check_schedule_wave2" ScheduleFrequency="Every 1 Months" ScheduleInterval="First Sat" ScheduleTime="20:00:00" ScheduleTimeDescription="Starting at 20:00:00" NextRunTime="2023-06-03 20:00:00" LastRunStatus="Successful" /> Instead of returning the whole conttens of the jobsinfo XML column SELECT JOBSINFO, hostname,* FROM DBO.SQL1 WHERE (jobsinfo.exist('/Jobs/Job[contains(@JobName,"Integrity_check_DBCC")]') = 1) Thanks in advance, [/INST]Try this: SQL SELECT JOBSINFO.query('/Jobs/Job[contains(@JobName,"Integrity_check_DBCC")]'), . . .</s>
<s>[INST]I am using SSMS, I want to copy 'created_datetime' column's values into another column within the same table. But There are two conditions 1] if the created_datetime column's value (datetime data type) is between 12:00am to 9:00am then we have to make it as 9:00am along with date. Ex- 2023-03-10 01:05:45 then we have to make it 2023-03-10 9:00:00 or 9:00 into another column 2] if the column's value is 2023-03-10 13:05:45 then we have to copy as it 2023-03-10 13:05:45 Note- Consider time between 12:00:00 to 9:00:59 then 9am. If not then copy as it. [/INST]](/users/na/?userid=482b28a6-e6dc-4a52-8897-d5f9b90ef8b4) Notice that your description of copy logic is slightly inconsistent. > between 12:00am to **9:00am** then we have to make it as 9:00am along with date. > Note- Consider time between 12:00:00 to **9:00:59** then 9am. If the second is a typo, then DATEPART will be fine. If not, then DATEPART should not be used here. Please try this solution: ```sql --Add new column to your table ALTER TABLE yourtable ADD new_column DATETIME; --Copy values to this new_column using UPDATE UPDATE yourtable SET new_column = CASE WHEN CAST(created_datetime AS TIME)>'9:00:59' THEN created_datetime ELSE DATEADD(hour,9,CAST(CAST(created_datetime AS DATE)AS DATETIME)) END ``` Also, you could update twice with different where conditions. ```sql UPDATE yourtable SET new_column = created_datetime WHERE CAST(created_datetime AS TIME) > '9:00:59' UPDATE yourtable SET new_column = DATEADD(hour,9,CAST(CAST(created_datetime AS DATE)AS DATETIME)) WHERE CAST(created_datetime AS TIME) < '9:00:59' ```</s>
<s>[INST]I have some multi-server jobs set up with both master (MyServer\MasterInstance) and target (MyServer\TargetInstance) on the same server but different instances. Both instances have the registry setting MsxEncryptChannelOptions set to 1. The target server status was showing Normal | Blocked with 11 Unread Instructions. Forcing Poll gave the error "This operation requires server to be a registered server". I confirmed that the target server is registered. I successfully ran sp_resync_targetserver for the target server. SP_POST_MSX_OPERATION: 1 DELETE download instruction(s) posted. SP_POST_MSX_OPERATION: 10 INSERT download instruction(s) posted. I Forced Poll again which showed successful. It successfully ran the delete instruction but nothing else. Next, I ran 'Delete from msdb.dbo.systargetservers' on the targer server and Forced Defection successfully. I added the target server back successfully with Normal status. I Forced Poll again successfully with status still showing Normal, but no instructions were executed, and the jobs were not created on the target. The next day, the target is back to showing Normal | Blocked again. So, what I know is that the instances are successfully communicating when the target server is resynced or when it is dropped and readded. In both cases, the delete instruction executes successfully, but none of the other instructions execute despite showing normal status and successful polling. The job error log on the target shows "An unresolved problem exists with the download instructions (sysdownloadlist) for target server 'MyServer\TargetInstance' at MSX 'MyServer\MasterInstance'". **EDIT: I ran select * from sysdownloadlist and found the following error: *The job step(s) could not be read (see the SQLServerAgent errorlog [at the target server] for details), or the job doesn't have any steps.* It turns out one of the jobs on the master did not have a job step in it. Once the step was there, the target eventually showed Normal status and the jobs synced successfully.** [/INST]\*\*EDIT: I ran select from sysdownloadlist and found the following error: The job step(s) could not be read (see the SQLServerAgent errorlog \[at the target server\] for details), or the job doesn't have any steps. It turns out one of the jobs on the master did not have a job step in it. Once the step was there, the target eventually showed Normal status and the jobs synced successfully.\*</s>
<s>[INST]Hi All, Trying to work on CLR objects. I have created dll from Visual studio using strong name. Now I need to create assembly for that new file. We already have CLR implemented for another dll. I want to use same assymetric key and user to create assembly and CLR SPs. I want to do this because key and user are already set up to be external_access and plumbing is done. I am not seeing any articles or resources that tells how to use existing asymmetric key for multiple dlls. Any help is appreciated. Thank You [/INST]you don't. there is a key (strong name) and user defined per assembly. this is how clr permissions are defined. note: the key is defined in the signed assembly.</s>
<s>[INST]How do you do something like this? ;with d as ( select * from dbo.a except select * from dbo.b ) delete from dbo.a select * from d [/INST]to delete the only the cte d rows from table a your delete needs a join to d sql with d as ( select * from dbo.a except select * from dbo.b ) delete from dbo.a a join d on a.key = d.key;</s>
<s>[INST]Hi All, Here are my query, please assist me to merge these two view in one Q1:   Select Table1.C1, Table2.C2, Table3.C3 FROM Table1 join Table2 Join Table3 Q2: Select Table4.C1, Table4.C2, Sum(C3), Sum(C4) FROM Table4 Group By Table4.C1, Table4.C1   How to merge this two view in one common fiels is Table1.C1 (Q1) and Table4.C1 (Q2) [/INST]](/users/na/?userid=dcd98708-4952-46d4-ba0f-6d73406fb8bc) First of all, there are a few things in your code that confuse me. In Q1. If you want to query C1 in table1, C2 in table2, and C3 in table3, the query statement should look like this. ```sql Select Table1.C1,Table2.C2,Table3.C3 FROM Table1,Table2,Table3; ``` In Q2. I guess you want to group by Table4.C1, Table4.C2. > How to merge this two view in one common fiels is Table1.C1 (Q1) and Table4.C1 (Q2) Since the two queries have a common field, I guess it should be using a table join. But I'm not sure which connection you need, inner join or left outer join or something else. I'll use inner joins as a demonstration. ```sql ;with T1 as( Select Table1.C1,Table2.C2,Table3.C3 FROM Table1,Table2,Table3 ),T2 as( Select Table4.C1,Table4.C2,Sum(C3) as sumc3,Sum(C4) as sumc4 FROM Table4 Group By Table4.C1, Table4.C2) select * from T1 as A inner join T2 as B on A.C1 = B.C1; ```</s>
<s>[INST]I know that while restoring the log backup, un-committed transactions will be recorded to the undo file and only committed transactions will be written to disk there by making users to read the database. When we restore next Tlog backup SQL server will fetch the un-committed transactions from undo file and check with the new Tlog backup whether the same is committed or not. If its committed the transactions will be written to disk else it will be stored in undo file until it gets committed or rolled back. But why there is need to store uncommitted transactions in TUF file as uncommitted transactions are already in memory of primary server. Please help [/INST]The memory on the primary server is not available on the log-shipping replica. And for that matter, the data from the uncommitted transactions does not have be in memory. If there is memory pressure, this pages may be flushed from the cache. Keep in mind that data is written to disk, even if the transaction is not committed. Yes, this means that there will be more work to do in case of a rollback, but the assumption is that transactions commit more often than they roll back. In the next transaction-log backup that is shipped there may be more data for this transaction, and there may also be the commit-mark. But the uncommitted transactions from the previous log-backup are not present in this backup. This backup only holds log records created after the previous back. This is how the log backup works. Keep in mind that the primary database has no knowledge the the logs are used for log shipping.</s>
<s>[INST]Hi All, I want to get number of Monday/Sundays till now in this year by writing SP. We can change dayname while executing as per need. But I am getting error while executing. Can anyone please look inti the below code and made required changes? ``` create proc countofMondays ( @BeginDate date = '20230101', @EndDate date = '20230404', @DayName VARCHAR(10) = 'Monday', @NumberOfMondays int output ) AS select @NumberOfMondays = (datediff(d, @BeginDate, @EndDate) + 1)/7 go declare @count int ``` [/INST]](/users/na/?userid=e65713be-e9aa-45b1-ae93-cb0d494b892e) You can use the datepart(wk,@EndDate) function, which will return the date in the week of the year. Using this function, I designed such a stored procedure, you can try it. ```sql create or alter proc countofMondays ( @EndDate date, @DayName VARCHAR(10), @NumberOfMondays int output ) AS if @DayName = 'Monday' begin set datefirst 1 select @NumberOfMondays = datepart(wk,@EndDate) - 1 end if @DayName = 'Sunday' begin set datefirst 7 select @NumberOfMondays = datepart(wk,@EndDate) end go Declare @NumberOfMondays int, @EndDate date = '20230404', @DayName VARCHAR(10) = 'Monday'; exec countofMondays @EndDate,@DayName,@NumberOfMondays output select @NumberOfMondays; ```</s>
<s>[INST]We are planning on upgrading to SQL 2022. We are currently on SQL 2017. Would I be able to add SQL 2022 to the SQL 2017 Availability Group and failover to it? I tried on a DEV environment and I see the database in (Synchronized / In Recovery) mode on the SQL 2022 server. SQL 2017 shows Synchronized. I see that the data is saved and transferred from SQL 2017 to SQL 2022. I did install SQL 2017 on the server that has SQL 2022 as I read somewhere that that would remove the In Recovery but it did not. Is AlwaysOn working even if the database states its in (Synchronized / In Recovery) mode? [/INST]you cannot fail over from SQL 2022 to SQL 2017. I'm not sure if you can add an SQL 2022 instance to an existing instance to an SQL 2017 AG. But the only reason you would have a mix of versions in an AG is that you perform a rolling upgrade. That is, you upgrade the secondary, then fail over the primary, and the upgrade the primary. I don't know if this is actually possible, but I think I've heard of people doing it. It is very important to understand that you can never move a database from a higher version to a lower version.</s>
<s>[INST]II have a table with some data, i can select the data i need with tsql. With ssis excute sql task, i could also do that. So what's the difference? Which one is more useful or advice.... [/INST]microsoft.com/en-us/users/na/?userid=2796236e-1215-45a9-9e51-8033f0069fc8) As far as I know, it makes no difference. `Excute SQL task` is to apply the execution result in SSIS. If your requirement is just to get data and view output in the SQL database, then use tsql will be fine. If you want to output the results to a local folder or other places, then SSIS is better.</s>
<s>[INST]I have managed to load data into a mssql database OK. On reading it out the results length is undefined. I suspect the data coming out isnt JSON so node doesnt know what to do with it. I can see the data if I json.stringify it but it needs to be in JSON format for my program to use it. Also if i "DROP TABLE xxxx IF EXISTS" the if exists causes a syntax error. mssql seems to have a lot of functionality missing. Have I missed something somewhere ? [/INST]I was running sql server 2012 so hopelessly out of date.</s>
<s>[INST]hi folks, I m creating a logon trigger to restrict any SQL login from a particular host. Following script is working as expected however its not flashing message as mentioned in the RAISERROR. When logon is denied the message user get is "logon failed for login 'xxx' due to trigger execution". Any idea how can i flash custom message? ``` CREATE TRIGGER [trigger_1] ON ALL SERVER FOR LOGON AS BEGIN IF (( left(host_name(),5) in ('XXX') ) and (SELECT name FROM sys.server_principals WHERE TYPE = 'S' and name = ORIGINAL_LOGIN()) is not null) BEGIN RAISERROR('Please login using windows authentication, SQL Authentication is refrained from workstation', 25, 1); ROLLBACK; END END ``` [/INST]Simple answer: You can't.</s>
<s>[INST]Hello, SQL Server - I realize there's an option in SSMS to Disable a Login account...but is Disabling it different than Locking it? (Locking a SQL Login account from what I understand is number of failed login attempts then gets automatically locked.) If yes they are different can I as a DBA manually Lock a SQL Login account (instead of disabling it) and how to do it ? Thanks in advance. [/INST]locking and disabling are different things. You disable an account with ALTER LOGIN DISABLE and re-enable it with ALTER LOGIN ENABLE. There does not seem to be any syntax to lock an account, but that can only happens because of a policy, for instance too many occurrences of the wrong password. It seems from the syntax graph that you can only unlock an account when you set the password.</s>
<s>[INST]We have a SQL server Standard configured as Failover Cluster with Always on High Availability Group. One server is Active and the other is Passive. Now, we have db1 which is replicated to Server2. What we want we want to add a db2 to Server2 and for db2 Server2 will be Active server and Server1 will be the passive server. What are the license requirements for this setup. If I buy another Standard License for Server2, will it be complaint? The SQL server licensing document doesn't answer my above scenario. Please advise. [/INST]](/users/na/?userid=10e35a5b-76be-4908-a7c6-1f2259c5508c)! If you have a two-node cluster, each node in the cluster must be licensed with a SQL Server Standard Edition license. This means that you would need to purchase an additional SQL Server Standard Edition license for Server2 in order to use it as the active server for db2. However, there are some additional licensing considerations for Always On Availability Groups. Each database that is participating in an Availability Group must be licensed with a SQL Server Enterprise Edition license, regardless of the edition of SQL Server that is being used for the Failover Cluster Instance. This means that if you want to use db2 in an Availability Group, you would need to purchase a SQL Server Enterprise Edition license for at least one of the nodes in the cluster.</s>
<s>[INST]EXEC sp_MSforeachtable @command1='SELECT ''?'' TableName' , @whereand='and ''?'' not in (''[dbo].[tblHolidays]'')' If I run the first line only, I get output including: TableName [dbo].[tblHolidays] If I run both lines, it does not exclude this table. What am I missing? [/INST]microsoft.com/en-us/users/na/?userid=804a1769-bffd-0003-0000-000000000000) If you just want to find table names that don't include [dbo].[tblHolidays], you don't need to split into two parameters. ```sql EXEC sp_MSforeachtable @command1='SELECT ''?'' TableName where ''?'' not in (''[dbo].[tblHolidays]'')' ``` I tried to use one parameter to achieve the desired effect and it seemed to be successful.</s>
<s>[INST]Hi all... it's not a really problem... but more a curiosity about the performances. I need to JOIN a "Multi-statement TVF" with other tables in a SELECT. I have 2 ways: 1. use a Multi-statement TVF 1. use a stored procedure into a #table, My function inside has multi insert, multi update, etc... it cannot be a iTVF for the complexity. ```tsql ALTER FUNCTION [dbo].[fnRelazioni_Gruppo_lis]( @SogCod numeric(8,0), @storico bit = 0, @RelTipCod varchar(10) ) RETURNS @rows TABLE ( ``` this is the approach with the stored (in the case of) `SELECT * INTO #temp_table FROM vw1 WHERE 1 = 0; ` `EXEC spRelazioni_Gruppo_lis INTO #temp_table;` or Since the first is called in a loop and returns only 1 row I preferred this way, knowing the limits of Multi-statement TVF and the table variables. Rather than relying on the number of rows (let's say 1000) I also count the number of columns or the general weight of the row. I exclude OLTP on-memory type tables... since I don't want to create complexity to the project that not only I manage. Is there some other way to dynamically bind, but still performant an external procedure (fn, mTVF, Procedure), with a group of tables in a JOIN of a select? Thanks Alen [/INST]I am not really sure what you are asking about. But generally, it can help to receive the result from a TVF in a temp table, rather than join directly with the TVF in a larger query. Obviously, the temp table comes with an overhead, but you get more accurate statistics, which means that your chances for a good query plan is better. Then again, the extra temp table adds complexity, and you may prefer to use the TVF directly in your main query, as long as performance is OK.</s>
<s>[INST]I would like to check if I need to install ODBC client drivers to access my MSSQL database on AWS cloud. Do I install the same client drivers that is used for database that is on premise?[/INST]Any special configuration or parameter for accessing database on cloud?</s>
<s>[INST]Hello. I need to consolidate the company's employees. I now have three tables, each with a unique EmpID, through which I want to concatenate the three tables. tableA contains basic information about individuals, names, etc. tableB contains contact information, etc., and some are empty. tableC contains simple family relationships, some are empty. Please recommend a suitable connection method. Thanks in advance. [/INST]microsoft.com/en-us/users/na/?userid=f41558c5-eeb0-4cb4-98e5-aca3ff322c57) According to your description, you can use the left outer join, like this. ```sql select * from tableA as A left outer join tableB as B on A.EmpID = B.EmpID left outer join tableC as C on A.EmpID = C.EmpID; ```</s>
<s>[INST]Hello I am trying to connect to SQL Server using C program on Linux. Server's IP is 192.168.0.25 and Port is 52000. I can connect to it using below: isql test ud pw -v My connection string is this: DRIVER = {ODBC Driver 17 for SQL Server}; Server = 192.168.0.25,52000;Database = db; UID = ud, PWD = pw; When I want to perform a test connection, I get this error: > [unixODBC][Microsoft][ODBC Driver 17 for SQL Server]Login failed for user '' Something must be wrong with the connection string because it shows empty user '', not 'ud' as in the string above. Why it does not pass my credentials? I'll be grateful for any help [/INST]Sorry for the comma instead of semicolon. I was retyping it from another machine so it was just a typo here. What in fact helped was to add those three options:</s>
<s>[INST]I have the following SQL query. My problem is the IIF at the end of the select statement. I get a invalid syntex near the \< SELECT TOP (100) PERCENT dbo.ictran.loctid, dbo.ictran.sono, dbo.ictran.palletno, dbo.ictran.item, SUM(dbo.ictran.tqty) AS tqty, dbo.sotran.descrip, dbo.sotran.custno, dbo.arspec.catalog AS custitem, dbo.icitem.plinid, SUM(dbo.icitem.weight \* dbo.ictran.tqty) AS pweight, dbo.icitem.weight, dbo.sotran.unitsper, SUM(dbo.ictran.tqty / dbo.sotran.unitsper) AS cartons, dbo.sotran.salesmn, dbo.icitem.upccode, dbo.icitem.eancode, dbo.icitem.barcode, dbo.icitem.barcodei, dbo.icitem.stkumid, dbo.icitem.unitsper AS mcarton, dbo.icitem.unitsperi AS incarton, SUM(IIF(dbo.ictran.tqty \< dbo.sotran.unitsper,dbo.icitem.stkumid, dbo.icitem.unitsperi,0)) FROM dbo.ictran INNER JOIN dbo.sotran ON dbo.ictran.sono = dbo.sotran.sono AND dbo.ictran.item = dbo.sotran.item INNER JOIN dbo.arspec ON dbo.sotran.custno = dbo.arspec.custno AND dbo.sotran.item = dbo.arspec.item INNER JOIN dbo.icitem ON dbo.ictran.item = dbo.icitem.item WHERE (dbo.ictran.sono \<\> ' ') AND (dbo.ictran.rfdone = 0) GROUP BY dbo.ictran.sono, dbo.ictran.loctid, dbo.ictran.palletno, dbo.ictran.item, dbo.sotran.descrip, dbo.sotran.custno, dbo.arspec.catalog, dbo.icitem.plinid, dbo.sotran.unitsper, dbo.sotran.salesmn, dbo.icitem.upccode, dbo.icitem.barcode, dbo.icitem.barcodei, dbo.icitem.eancode, dbo.icitem.stkumid, dbo.icitem.weight, dbo.icitem.unitsper, dbo.icitem.unitsperi ORDER BY dbo.ictran.sono, dbo.ictran.palletno, dbo.ictran.item [/INST]This is what I ended up with, and it seems to work SELECT TOP (100) PERCENT dbo.ictran.loctid, dbo.ictran.sono, dbo.ictran.palletno, dbo.ictran.item, SUM(dbo.ictran.tqty) AS tqty, dbo.sotran.descrip, dbo.sotran.custno, dbo.arspec.catalog AS custitem, dbo.icitem.plinid, SUM(dbo.icitem.weight \* dbo.ictran.tqty) AS pweight, dbo.icitem.weight, dbo.sotran.unitsper, SUM(dbo.ictran.tqty / dbo.sotran.unitsper) AS cartons, dbo.sotran.salesmn, dbo.icitem.upccode, dbo.icitem.eancode, dbo.icitem.barcode, dbo.icitem.barcodei, dbo.icitem.stkumid, dbo.icitem.unitsper AS mcarton, dbo.icitem.unitsperi AS incarton, SUM(CASE WHEN dbo.ictran.tqty \< dbo.sotran.unitsper THEN dbo.ictran.tqty / dbo.icitem.unitsperi ELSE dbo.ictran.tqty / dbo.sotran.unitsper END) AS cartons FROM dbo.ictran INNER JOIN dbo.sotran ON dbo.ictran.sono = dbo.sotran.sono AND dbo.ictran.item = dbo.sotran.item INNER JOIN dbo.arspec ON dbo.sotran.custno = dbo.arspec.custno AND dbo.sotran.item = dbo.arspec.item INNER JOIN dbo.icitem ON dbo.ictran.item = dbo.icitem.item WHERE (dbo.ictran.sono \<\> ' ') AND (dbo.ictran.rfdone = 0) GROUP BY dbo.ictran.sono, dbo.ictran.loctid, dbo.ictran.palletno, dbo.ictran.item, dbo.sotran.descrip, dbo.sotran.custno, dbo.arspec.catalog, dbo.icitem.plinid, dbo.sotran.unitsper, dbo.sotran.salesmn, dbo.icitem.upccode, dbo.icitem.barcode, dbo.icitem.barcodei, dbo.icitem.eancode, dbo.icitem.stkumid, dbo.icitem.weight, dbo.icitem.unitsper, dbo.icitem.unitsperi ORDER BY dbo.ictran.sono, dbo.ictran.palletno, dbo.ictran.item</s>
<s>[INST]Fellow DBA's I am trying to research what statistics a query is using. I am on SQL 2016 I realized that 9204 is for older versions. Some writings indicate that 9204 has been replaced by 2363. When I run with options 3604 and 2363 and recompile, I do get output about stats but no where in that mess is the name of the statistics that are being used. What am I missing? thx MG[/INST]Found it, It shows the stats ID number, then you go find which stats ties to that number.</s>
<s>[INST]Hi, In our application we think of using what we can call long life cursors. These are application-side cursors (not server-side cursors) that will be openned by/for the end user and read according to the end user needs. If the end user don't scroll to the end of it, this cursor will not be read entirely and will not be closed. All non-closed cursors will be closed when the application will be closed. But if the application is not closed, this will lead to cursors openned for a long time. Can/Will this design lead us into problems? What kind of problems? Best regards. Carl [/INST]I certainly get nervous when I read this. There is a risk that the user will hold locks on the rows that then could block writes unless the database is in read_committed_shapshot. Also, I can't say that I find this a very modern design. I would rather read all rows into to memory once. If the dataset is large, let's say thousands of rows, I would consider paging.</s>
<s>[INST]We want to replicate rows and populate product code from mapping table. My sample table structure is as below. We have #tb_RawData table in which we received from another team. We have #tb_productmapping mapping table in which we has product type and product code. To populate [Product Type] in final Output we want to match the column header of the #tb_RawData with the #tb_productmapping (column product) eg. We match the column header [Elect Prd] of #tb_RawData with the [Product[ column of #tb_productmapping and get the [Product Type] as 'Electronic' We want to replicate all rows from #tb_RawData and populate product code in our #tb_final table. Also I have attached the screen shot of RawData, Mapping Table, Final Output. I am thinking of writing loop for this but we have around 10000 rows and 50 columns in raw data table Is there any other better way to solve this problem ---------------SQL Scripts /* RAW DATA */ IF OBJECT 1D ("tempdb..#tb RawData') IS NOT NULL DROP TABLE #tb_RawData CREATE TABLE #tb_RawData ([Customer] VARCHAR (255), [Books prd] TINYINT, [Elect Prd] TINYINT, [Food Prd] TINYINT) INSERT INTO #tb_RawData values (1,11,21,0) INSERT INTO #tb_RawData values (2,0,0,31) --select * from #tb_RawData /* Mapping Table */ IF OBJECT ID('tempdb..#tb productmapping') IS NOT NULL DROP TABLE #tb_productmapping create table #tb_productmapping ( product varchar (255), producttype varchar (255) ) insert into #tb_productmapping values ('Books prd', 'Books') insert into #tb_productmapping values ('Elect Prd','Electronic') insert into #tb_productmapping values ('Food Prd','Food') --select * from #tb_productmapping /* Final output */ IF OBJECT ID('tempdb..#tb_final') IS NOT NULL DROP TABLE #tb_final create table #tb_final (Customer varchar (255), [Product Type] varchar (255), [Books prd] TINYINT, [Elect Prd] TINYINT, [Food Prd] TINYINT) insert into #tb_final values (1,'Books',11,0,0) insert into #tb_final values (1,'Electronic',0,21,0) insert into #tb_final values (1,'Food',0,0,0) insert into #tb_final values (2, 'Books',0,0,0) insert into #tb_final values (2,'Electronic',0,0,0) insert into #tb_final values (2, 'Food',0,0,31) --select * from #tb_final[/INST]](/users/na/?userid=a4bfd646-05fa-4a5c-a14a-74f6d6307929) How about this? sql DECLARE @sql_str VARCHAR(MAX) DECLARE @column_header VARCHAR(MAX) DECLARE @CaseWhen_str VARCHAR(MAX)='' SELECT @column_header = ISNULL(@column_header + ',','') + QUOTENAME(product) FROM #tb_productmapping GROUP BY product --PRINT @column_header SELECT @CaseWhen_str = @CaseWhen_str + ',CASE WHEN Product_Amount='+QUOTENAME(product)+' THEN Product_Amount ELSE 0 END AS ' + QUOTENAME(product) FROM #tb_productmapping GROUP BY product --PRINT @CaseWhen_str SET @sql_str = ' SELECT C.Customer,ProductType '+@CaseWhen_str+' FROM (SELECT *FROM #tb_RawData UNPIVOT(Product_Amount FOR Product IN ('+@column_header+'))U) C JOIN #tb_productmapping P ON C.Product =P.product JOIN #tb_RawData R ON C.Customer=R.Customer' --PRINT (@sql_str) EXEC (@sql_str)</s>
<s>[INST]Hello, I am running SQL Server Express (2017) with SQL Server Management Studio (V18.8). As login = **User**, I used server login and create a sample database "Chinook". It works fine. But I exit and login again using Windows Authentication, which implicitly for **User**, I cannot access that database. Can you please tell me how to resolve it? An issue could be related to the above issue is that I login as **desktop administrator login** to SQL Server Management Studio, and grant **User** the permission to create database. But when I use Windows Authentication, I cannot create database. Instead I have to use server login as **User** to create the database Chinook. When I login as my **desktop administrator login**, I find the create database permission check box for **User** is unchecked. Thank you! [/INST]I uninstalled the existing SQL Server Express, and SQL Server Management Studio, and installed SQL Server Express 2019 and SQL Server Management Studio 18.8. Then I found the correct login full name for **User** is [BUILTIN\Users]. With this [BUILTIN\Users] and using Windows Authentication I can create and access databases without issue after grant proper permissions.</s>
<s>[INST]Hello, I have scheduled a recompile for few of my procs like this **exec sp_recompile [proc_name]**. I want to do the same thing with an adhoc query, currently I manually re-compile it in case of any issues by using dbcc freeproccache(plan_handle) however I want to automate it and regularly clean the plan cache of the adhoc query. P.S I believe optimisation is a long term resolution however in this case the adhoc query is scheduled to be deprecated in few weeks and I don't want to spend much of my time in optimising it. [/INST]](/users/na/?userid=d0602611-fa0b-45db-bf9d-d914ab7ef8ed) if this is just a temporary solution why not automating the process with this query select cp.plan_handle from sys.dm_exec_cached_plans cp cross apply sys.dm_exec_sql_text(cp.plan_handle) st where st.text = '<YourAdhocQuery or GUID you plant into the query to help with searching for the query>' this will help you get the plan handle for your adhoc query and then you can use the dbcc command to evacuate it from plan cache.</s>
<s>[INST]I'm prepping to install SQL Server 2019 Always On availability group cluster. Part of the install is to specify database mirroring endpoints for each SQL instance. In the past, I used ports 5022, 5023, 5024, etc, for the endpoints for multiple instances. I saw a recent MS article with an example that uses 7022 for the endpoint. When I look up the TCP port descriptions, I see: 5022 = "MSSQL Server Replication and Database mirroring endpoints" 7022 = "Database mirroring endpoints". What's the difference? Does it matter which port(s) I use? Thanks. [/INST]you can use any port, as long as that port is not use by any other program in the machine. The only purpose these "official" port designation serves is exactly to avoid such collisions.</s>
<s>[INST]Hello I have Server A (Windows server 2008 R2, SQL Server 2008 R2) I need to migrate my database to Server B (Windows Server 2016 with SQL Server 2016) In my Server A. I have many API, developer projects, connectios, etc... What is the best advise to do? Z) reconnected all my conecctions, APIs, developer projects, with the new instance and credentials? Y) configure Server B, with the same instance, HOSTNAME, and credentials(user=sa, passwd=***)? This last option(Y), even if I rename the same credentials, hostname and instance my Server B. I need to reconnected all? [/INST]As they say, it depends. Many people would do Y. That is, install the new server as the old server and cut over. This will require some downtime, though, since you are likely to run into problems, if you have two machines on the network with the same name. So you would have to shut down the old server before you copy. Or, well, you could rename the server once you are satisfied. This requires one extra step in SQL Server: ```sql EXEC sp_dropserver OLDNAME EXEC sp_addserver NEWNAME, 'local' -- Restart SQL Server after this. ``` However, there is one thing in your post, which makes me think that you should go for Z. Your post suggests that applications are connecting with sa. That is very bad, and that is something you would need to fix if this is the case. The server upgrade could serve as a kick in the rear parts to do that action. And I should hasten to add that connection should not be by any other sysadmin account. Applications should connect only with permissions to run stored procedures and possibly read/write data in tables.</s>