Quantcast
Channel: Transact-SQL forum
Viewing all 23857 articles
Browse latest View live

create stored procedure to execute on a remote machine

$
0
0

Hi, I am using the below query and works fine.

DECLARE @ProductName nvarchar(250) = 'Camera', @ProductDescription nvarchar(250) = 'DSLR camera'

DECLARE @query NVARCHAR(MAX)

    SET @query = 'EXEC (''INSERT INTO [dbo].[Products] ([ProductName], [ProductDescription]) VALUES (?,?)'',''' + @ProductName + ''',''' + @ProductDescription + ''') AT [linkedserver]'   PRINT @query -- EXEC ('INSERT INTO [dbo].[Products] ([ProductName], [ProductDescription]) VALUES (?,?)','Camera','DSLR camera') AT [linkedserver]

But when I try to write the same query as a stored procedure and do a jdbc call the stored procedure does nothing.

CREATE PROCEDURE [dbo].[testsp] @ProductName nvarchar(250), @ProductDescription nvarchar(250)
AS

DECLARE @query NVARCHAR(MAX)

    SET @query = 'EXEC (''INSERT INTO [dbo].[Products] ([ProductName], [ProductDescription]) VALUES (?,?)'',''' + @ProductName + ''',''' + @ProductDescription + ''') AT [linkedserver]'   EXEC sp_executesql @stmt = @query

In the javascript application call the stored procedure as below.

call [dbo].[testsp](?,?)

The stored procedure does not throw any errors as such nor does it insert data. Could please point me if I am missing something.

Thank you in advance.


SQLEnthusiast


Compare table counts inside a stored procedure - Please help!

$
0
0
Hi,
I am new to SQL.

My requirement is below and I need to do this inside a stored procedure -

I have to compare two tables count- Employee & EMployee_Old

If count(Employee) table is greater, 
then Drop EMployee_Old
else Drop EMployee & Rename  EMployee_Old to EMployee

Can you please help me to derive this logic inside a Stored Procedure?

subtract the column values based on the input value

$
0
0

declare @t table ( id int, Value int ) insert into @t select 1,10 union select 2,12 union select 3,3 union select 4,15 union select 5,23 union select 6,10 select * from @t

Above is the my table script and if I give value 26 then it should be subtract from the 'value' column.

Below is the expected out put 



First the input value should be subtract the first 'id'

input value --> 26 

id#1 --> 0 (26-10)

id#2 --> (16-12)

id#3 --> 0(4-3)

id#4 --> 14 (1-15)

Can we do it with out While loop?


Deadlock due to Shared lock acquiring on parent table

$
0
0

We are getting deadlock when we update a child table by using primary key in where condition . the deadlock graph show that a shared lock was acquiring  on parent table in one execution and and in other execution it is acquiring  exclusive lock.

why the update is locking the parent table , is there any way to avoid the parent table locking .

sample code 

update table1

   id  =@va

where table1_PK=@value

here in id column we have defined a fk which reference another table 

How to delete records from table trade code that No have parent code value and parent code type ?

$
0
0
I work on sql server 2012 I need to delete rows 

Insert/Update XML file in SQL column

$
0
0

Hi, I have a table which has multiple Columns say FName, LName, City, XMLFile

FName is type varchar(20), LName is type varchar (20), City is type varchar(20)

XMLFile is of type XML.

Is there a easier way to insert or update the complete XML file  in SQL column ?

Please advise


Reason101

Reparented Hierarchy tree to generate next sequential HID

$
0
0

I want to work out to create next hierarchy sequence id when reparenting hierarchy tree

i.e.

HID tree /3/, /3/1/, /3/2/, /3/2/1/, /3/2/2/, /3/2/3/

Reparenting /3/2/.... tree to /5/ will remain /5/2/ and it's subsequent series.

Is there any way when we can start /5/1/ if there is no child and if any child get next HID i.e /5/2/ and so on.

Thanks


DA

SELECT * Result into a string ?

$
0
0

Hi !

This is for an attempt at a  trigger script that will be on many *different* tables, thus I do not know number of columns, their names or their data types. That is why I am looking for SQL Server to get the Select result as an output string.

Is it at all possible to get a "SELECT * FROM inserted" result into a string WITHOUT looping the inserted table or some object ?
I was hoping for some internal function that could do it or if there is some clever other way.

Thanks !

BR Scand



Fetching all rows in a triggers 'inserted' table possible?

$
0
0

Hi !

I am using SQL Broker Service with contracts etc and in the update trigger of a table is the code below, however it only fetches 1 row from the inserted table and sends it as xml by message.

My question is how to get all rows in 'inserted' and sending them as an xml message *without* having an outer WHILE LOOP ?

SET @MessageBody = (SELECT Id, uuid, Misc1, Misc2, Date, Dept FROM inserted
FOR XML AUTO)              

If (@MessageBody IS NOT NULL)
BEGIN

DECLARE @Handle UNIQUEIDENTIFIER;  
BEGIN DIALOG CONVERSATION @Handle  
FROM SERVICE [TestServiceInitiator]  
TO SERVICE 'TestServiceTarget'  
ON CONTRACT [TestContract]  
WITH ENCRYPTION = OFF;  
SEND ON CONVERSATION @Handle  
MESSAGE TYPE [TestMessage](@MessageBody);
END

Best Regards, Scand



Time out error while creating Index

$
0
0

Getting timeout error while creating a index which uses partition schema. Tried changing the transaction time out value for table designer in SSMS but it did not work .

CREATE CLUSTERED INDEX IX_Indexname ON  dbo.order ([MONTH ID])
WITH (STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
  ON Month_PS([MONTH ID])

Problem in apportion

$
0
0

Hi guys, 

I have a big problem wit the apportion. The sum of the percentage is always 99.1 / 99.2 and this is not acceptable. The percentage comes from something like this

with zz (

select sum (TotF) TF, pp from TableOne group by pp)

select pp, TF*OldValue as percentage from azz inner join....

where totF is numeric (18,3) and OldValue is numeric (38,10). i changed today the OldValue from numeric(38,6) to numeric (38,10). 

The query above is (as example) my view and if I see the property of the view the column percentage is numeric (38,6). 

I would like to have a numeric 38,10 or 38,12 so I can have a more accurate percentage and a more meaningful total (not 99.1 or 99.2 but at least 99.8/99.9)

Any advice?

How to mention dynamic column name in dynamic pivot

$
0
0

here i am giving my SP where dynamic column name causing issue

ALTER PROCEDURE [dbo].[USP_GET_NewPeriodData]      
 -- Add the parameters for the stored procedure here      
 @Ticker VARCHAR(10),
 @Periods VARCHAR(MAX)
AS      
BEGIN      
 -- SET NOCOUNT ON added to prevent extra result sets from      
 -- interfering with SELECT statements.      
 SET NOCOUNT ON;      

 DECLARE @columns NVARCHAR(MAX)      
 DECLARE @sql NVARCHAR(MAX)      
 

SELECT @columns =
COALESCE(@columns + ', ','') + QUOTENAME([Name])
FROM
   (
 Select e.ID, ISNULL(Period,'') [Name]      
 From tblCalenderMaster AS d INNER JOIN      
 tblCalenderDetail AS e ON d.ID = e.MasterID      
 Where e.IsDeleted!='Y' AND d.TickerID=@Ticker AND e.Period IN (@Periods)   
 Group By e.ID, Period 
   ) AS B
ORDER BY B.Name
 PRINT STUFF(@columns,1,0,'')
 SET @sql = N'      
 Select Ticker,Section,LineItem,XFundCode,OrderID ,'+STUFF(@columns,1,0,'')+'      
 From (      
  SELECT b.Ticker, b.Section, c.LineItem,XFundCode,OrderID,bg.[Values] Val, e.Period [Name]      
  FROM tblTicker_Bogey AS bg INNER JOIN      
   tblSectionLineItemTemplate AS a ON bg.SectionID=a.SectionID AND bg.LineItemID=a.LineItemID INNER JOIN       
   tblSectionTemplate AS b ON a.SectionID = b.SectionID INNER JOIN      
   TblLineItemTemplate AS c ON a.LineItemID = c.ID INNER JOIN      
   tblCalenderMaster AS d ON b.Ticker = d.TickerID INNER JOIN      
   tblCalenderDetail AS e ON d.ID = e.MasterID      
  WHERE (bg.[Values] IS NOT NULL) AND  (a.Active = ''A'') AND (e.IsDeleted <> ''Y'') AND b.Ticker='''+@Ticker+''' AND bg.PeriodID=e.ID      
   AND bg.MasterID=d.ID      
 )X PIVOT (MAX(Val) FOR [Name] IN ('+STUFF(@columns,1,0,'')+')) AS p      
 ORDER BY OrderID     
 '      
print @sql  

--EXEC(@sql)      
      
END 

specially see this line Where e.IsDeleted!='Y' AND d.TickerID=@Ticker AND e.Period IN (@Periods)   

the moment i add  e.Period IN (@Periods)  then nothing is working. how to sort this issue?

calling the SP this way

 DECLARE @Periods VARCHAR(MAX) = '''1Q 2020'',''2Q 2020'', ''3Q 2020'''
 EXEC [USP_GET_NewPeriodData] 'AAPL',@Periods


Performance Tuning - SQL

$
0
0

Hi All, 

I have been struggling to understand this query , however I have to rewrite it to improve the performance as tabe has records in millions and can not afford multiple joins to the same table.

SELECT DISTINCT 1.A_ID 
FROM ABC 1
INNER JOIN ABC 2 ON 1.ID = 2.ID
INNER JOIN ABC 3 ON 3.ID = 2.MATCH_P_ID
LEFT OUTER JOIN OTHER_TABLE O ON  O.SOME_COL = 2.SOME_COL
WHERE 1.TYPE =1 AND O.VALUES IN ( 100,101,102)


I do not have an execution plan and no idea about indexes on the table, I will reach out to DBAs to see that  ,however I want to know if anyway rewriting can happen here.

Thank you !





Row Number - reset for repeated value

$
0
0

Hi I have to generate row number, for Rating column. And it has to be orderd by submitted date. When the value repeats row number should reset to 1. Please look at below example. This is sample set of data, i have thousands of deals like this in the table to handle. I tried with Row_Number,Rank and Dense_Rank too like below:

row_number() over(partition by Rating,[Original Id] order by [Original Id],[Submitted Date] asc) as [Row Number]

IDOrignal IDSubmitted DateRatingRating 2Rating 3Row NumberExpected
22323134443/18/2020582452
217061344412/30/2019652521
215931344412/18/2019752577
215631344412/17/2019752566
213041344411/25/2019752555
208291344410/8/2019752544
20720134449/27/2019752533
20527134449/9/2019752522
20004134447/9/2019752511
19848134446/21/2019652511
19690134446/4/2019582444
19379134444/23/2019582433
19151134443/22/2019582422
18937134442/19/2019582411
18545134441/7/2019522488
18522134441/2/2019522477
182411344412/7/2018522466
181961344411/30/2018522455
16150134443/27/2018522444
15992134442/27/2018522433
15655134441/5/2018522422
13444134443/6/2017522411

Thanks

Manoj

Challenge with Linking

$
0
0

I'm trying to link 3 tables and produce one summary line with different level groupings.  The best way to make this clear is to provide an example.  Table names are underlined.  Example data is in brackets.

Item Master
Item Number
Qty on Order
[Widget, 2]

PO
PO Number
Item Number
Qty Ordered
[PO1, Widget, 5]
[PO2, Widget, 5]

Receipts
PO Number
Item Number
Qty Received
[PO1, Widget, 2]
[PO1, Widget, 1]
[PO2, Widget, 5]

The results should be one row per item number. Based on the above info, that would be as follows:

Results
Item Number [Widget]
Qty on Order [2]
Qty Ordered [10]
Qty Received [8]

We are troubleshooting instances where the Qty on Order does not match the Qty Ordered - Qty Received.  The above example ties out.

My challenge is the three layers.  There are multiple POs for each item.  And then multiple receipts for each PO.


Cindy


SQL Store procedure to run PowerShell commands ( need to add active directory user to security Group)

$
0
0

we have the list of the new members in CSV file (coming every week to update)

the CSV file name is c:\scripts\members.csv

and have two columns

GroupName                   Member

SG-BI-USERS                 XXXXX@ABC.ORG

SG-BI-USERS                  YYYYY@ABC.ORG

SG-BI-USERS                  ZZZZZ@ABC.ORG

the powershell screipt to add the member to security group command is below 

$csv = Import-Csv -Path "c:\scripts\members.csv"<o:p></o:p>

ForEach ($item In $csv) {  $Add_group = Add-ADGroupMember -Identity $item.GroupName -Members $item.Membername }

Or

using  Exchange PowerShell.

import-Csvc:\scripts\members.csv | Foreach {Add-ADGroupMember -Identity $_.Group -Members $_.Member}

<o:p style="">Note: USER Credential  to update/insert the members to security group is  ABC\poweruser1   password= xxyyzz</o:p>

The Question is how to write/include this powershell scripts in store procedure?

or write a sql store procedure to run this powershell command ..


Shrink Log Files

$
0
0

Hi,

We are seeing issue with one of our production server Log file getting filled up. Some transaction is filling up the space. How do I identify the long running transaction when it runs ? Its mostly from one of the jobs that run late night.

Also how can I automate a script to Shrink Logfiles ? I did using SSMS but would like to see if there is any way through T SQL and automate to run every few hours?


sami


Getting dynamically values separated by commas

$
0
0

Hi there,

In a query, imagine you need to get the values separated by commas in a dynamic column where you have sometimes four, five or six values.

Let me show you:

--declare @core_value varchar(200) = 'microwave,oven,dish_washer,refrigerated,pressure_cooker,steamer';
declare @core_value varchar(200) = 'microwave,oven,dish_washer,refrigerated';


--getting the number of commas plus 1 in order to know in advance how many values need to split out
SELECT (LEN(@core_value) - LEN(REPLACE(@core_value, ',', ''))) + 1  as Number_of_Times

SELECT dbo.GetColumnValue(@core_value, ',', 1) as Product_Support_Devices1
,dbo.GetColumnValue(@core_value, ',', 2) as Product_Support_Devices2
,dbo.GetColumnValue(@core_value, ',', 3) as Product_Support_Devices3
,dbo.GetColumnValue(@core_value, ',', 4) as Product_Support_Devices4
,dbo.GetColumnValue(@core_value, ',', 5) as Product_Support_Devices5
,dbo.GetColumnValue(@core_value, ',', 6) as Product_Support_Devices6

If you run the above query you will get "Product_Support_Devices5" and "Product_Support_Devices6" with fake values, in fact they don't exist, however the UDF (below) extract a value not a NULL

UDF am I using:

CREATE FUNCTION dbo.GetColumnValue(
    @String VARCHAR(MAX),
    @Delimiter CHAR(1),
    @Column INT = 1
)
RETURNS VARCHAR(MAX)
AS    
BEGIN
DECLARE @idx INT
DECLARE @slice VARChar(MAX)     
SELECT @idx = 1     
    IF LEN(@String)<1 OR @String IS NULL
        RETURN NULL
DECLARE @ColCnt INT
    SET @ColCnt = 1
WHILE (@idx != 0)
BEGIN    
    SET @idx = CHARINDEX(@Delimiter,@String)     
    IF @idx!=0 
    BEGIN
        IF (@ColCnt = @Column) 
            RETURN LEFT(@String,@idx - 1)        
        SET @ColCnt = @ColCnt + 1
    END
    SET @String = RIGHT(@String,LEN(@String) - @idx)     
    IF LEN(@String) = 0 BREAK
END
RETURN @String  
END

So the idea is getting real values not repeated ones

Thanks for your inputs/hints

Enric


SQL help

$
0
0

Hi All,

Thank you for helping others who are in need.

I have a requirement where i need to calculate the calc_wrkhrs field (which is in mustard color) from the attached excel

I have 3 tables Payrolltable, Census table and quickbasetable

Based on the quick base table the values in workedhrs column the hours should sum up from Payroll table.

1- Regular is always comes in Payroll Table (this we can sum up with no issue) in the excel i did not sum up this

for ex

for employeid 2180, pay group  YOR, and Unicode  VA4-NOCBA : the column 'workedhours' has values  22- Training, 20 -Holiday (please ignore 1- Regular (this is a compulsary column in Payrolltable only other columns will vary) 

 Pick these values 22- Training, 20 -Holiday Worked match to hrs_22 and hrs_20 columns in Payroll table and provide the sum

the color blue and green in the excel determines the how the values are associated with unicode 

Please find the required code for the table creation and attached the excel for reference to  give an idea.

Thank you in Advance

create table quickbase (
paygroup varchar(3),
unioncd varchar(20),
workedhrs varchar(8000)
)
insert into quickbase values ('Y0R','VA4-NOCBA','1 - Regular;22 - Training;20 - Holiday Worked');
insert into quickbase values ('Y0R','NJ2-WJHTCS','1 - Regular;22 - Training;20 - Holiday Worked;HLW - Holiday Worked;GM - Guard Mount');

create table census (
paygroup varchar(3),
empid bigint,
unioncd varchar(20) ) 
insert into census values ('Y0R',21840,'VA4-NOCBA')
insert into census values ('Y0R',19948,'NJ2-WJHTCS')

create table payroll (
paygroup varchar(3),
empid bigint,
rg_hrs decimal(20,0),
hrs_20 decimal(20,0),
hrs_22 decimal(20,0),
hrs_hlw decimal(20,0),
hrs_gm decimal(20,0),
upd_date datetime default getdate()
)
truncate table payroll
insert into payroll(paygroup,empid,rg_hrs,hrs_20,hrs_22,hrs_hlw) values ('Y0R',21840,5,0,5,10);  --- 1 emp can have multiple recs in payroll table 
insert into payroll(paygroup,empid,rg_hrs,hrs_20,hrs_22) values ('Y0R',21840,70,8.0,0); --- 1 emp can have multiple recs in payroll table 
insert into payroll(paygroup,empid,rg_hrs,hrs_20,hrs_22,hrs_hlw,hrs_gm) values ('Y0R',19948,75,12.0,11.0,5,4);


nethan

Shrink Operation

$
0
0

Hi All,

Today I was checking a database log file full issue. {The transaction log for database 'XXX' is full due to 'LOG_BACKUP'}

Found log backup was never taken on the database. So issued log backup manually & after that there was 99% free space available on the log file.

Immediately after taking log backup, I was trying to shrink the file. But by mistake, instead of choosing the reorganize option & I have clicked on option 'empty file by migrating data to other files in the same file group'.

There is only one log file present on the DB. I am worried, if it would have caused any data loss. Please suggest.

Thank You!



Viewing all 23857 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>