jeudi 30 juin 2016

Executing stored procedure with parameters SQL 2005

I have the following stored procedure below. When I try to execute the stored procedure with this code; exec [transport].[dbo].[Delivery_Manifest_email] @RunNo = '3'

I get the following error - Msg 8146, Level 16, State 2, Procedure Delivery_Manifest_email, Line 0 Procedure Delivery_Manifest_email has no parameters and arguments were supplied.

I’m trying to pass the @RunNo parameter and I can’t see why my syntax is wrong? The stored procedure executes fine when I manually set @RunNo parameter in the stored procedure itself. I don’t want to do it this way though. SQL server is 2005.

**USE [Transport]
GO

/****** Object:  StoredProcedure [dbo].[cutting_data_SP]    Script Date: 06/30/2016 15:56:12 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Delivery_Manifest]
AS 

DECLARE @tableHTML  NVARCHAR(MAX);
DECLARE @HTMLBody NVARCHAR(MAX)  
DECLARE @XML NVARCHAR(MAX)
DECLARE @s NVARCHAR(MAX)
DECLARE @Driver NVARCHAR(MAX)
DECLARE @Lorry NVARCHAR(MAX)
DECLARE @recip NVARCHAR(MAX)
DECLARE @varCheck BIT
DECLARE @DueDate VARCHAR(10)
DECLARE @RunNo NVARCHAR(MAX)
SET @DueDate = '27/06/2016'
SET @Driver = 'Test
SET @Lorry ='Test'
SET @s = 'Delivery Manifest for:  ' +CONVERT(VARCHAR(12),GETDATE(),107) +', Run number  '+@runno + ',  ' +@Driver +',  ' +@lorry
set @recip = 'test@test.co.uk' 

IF EXISTS (SELECT        
[OrderNoOnManifest] ,[Lorry], [Driver], [Name] ,[Town], [POSTCODE] ,[Telephone],[DELIVERY NOTE] ,[Notes], [Shipping Weight (Kg)], [PackagingLength],[District] , [ServiceLevel] ,[SpecificDelTime] 
FROM [Transport].[dbo].[DELIVERY_MANIFEST_MASTER]
WHERE [Due Date] = @DueDate and [Run No] = @RunNo
                     )

    SET @tableHTML = '<style type="text/css">
table.tftable {font-size:12px;color:#333333;width:100%;border-width: 1px;border-color: #9dcc7a;border-collapse: collapse;}
table.tftable th {font-size:12px;color:#ffffff;background-color:#ff1a00;border-width: 1px;padding: 8px;border-style: solid;border-color: #9dcc7a;text-align:left;}
table.tftable tr {background-color:#ffffff;}
table.tftable td {font-size:12px;border-width: 1px;padding: 8px;border-style: solid;border-color: #9dcc7a;}
</style>
  <body>
  '
+ @s +'<p style="text-align:left;"><span style="font-family:Helvetica;font-size:12px;font-style:normal;font-weight:normal;text-decoration:none;text-transform:none;color:000033;"> </span>
</p>
<br>
<table class="tftable" border="2">'          
   + N'<th>Order</th>'
         + N'<th>Customer</th>'
          + N'<th>Town</th>'
+ N'<th>Postcode</th>'
  + N'<th>Tel. No.</th>'
   + N'<th>Order No</th>'
           + N'<th>Notes</th>'
  + N'<th>Weight (Kg)</th>'
     + N'<th>Dimension</th>'
          + N'<th>Instructions</th>'
  + N'<th>Service Level</th>'
  + N'<th>Delivery Time By</th></tr>'
  + CAST ( (  SELECT 
                   td = [OrderNoOnManifest], ''
                           , td = [Name] , ''
                             , td = [Town],  ''
                              , td = [POSTCODE] ,''
                               , td = [Telephone],''
                                  , td = [DELIVERY NOTE],''
                                    , td = [Notes],''
                                     , td = [Shipping Weight (Kg)],''
                                     , td = [PackagingLength],''
                                     , td = isnull([District],'None'),''
                                     , td = isnull([ServiceLevel],0),''
                                      ,td = isnull([SpecificDelTime],0),''
FROM            [Transport].[dbo].[DELIVERY_MANIFEST_MASTER]
WHERE [Due Date] = @DueDate and [Run No] = @RunNo
ORDER BY [OrderNoOnManifest] asc
                                                    FOR
                                                     XML PATH('tr')
                                                       , TYPE
                                                   ) AS NVARCHAR(MAX)) + N'</table>'

+'<br>'
+'<br>'
+  '<p style="text-align:left;"><span style="font-family:Helvetica;font-size:12px;font-style:normal;font-weight:bold;text-decoration:none;text-transform:none;color:000033;">TEST DELIVERY MANIFEST EMAIL</span>

'
BEGIN

    EXEC msdb.dbo.sp_send_dbmail 
   @blind_copy_recipients = @recip, 
    @profile_name = 'Test',  
    @subject = @s,
        @body = @tableHTML, 
        @body_format = 'HTML' ;

END**

Export Linked Server Properties Using SQL Script

Can anyone please help me to know how can I script out the linked server properties (refer to below image) using SQL Script?

enter image description here

When can DBCC FREESYSTEMCACHE (‘TokenAndPermUserStore’) hang in SQL Server 2005

We are running production DB servers on SQL Server 2005 and we ran into high TokenAndPermUserStore issue which caused the delay in running queries. There is a scheduled job on the SQL server which runs every 1 hour and performs the DBCC FREESYSTEMCACHE (‘TokenAndPermUserStore’) however this job was hung for many hours and had to be eventually killed. What are the possible reasons that a DBCC FREESYSTEMCACHE gets hung for so long. Can the incoming queries cause it?

Execute a SQL query/statement conditionally based on table data

First, take a look at this table, basically I need to UPDATE (+1) a ticket WHERE the Username equals to Jondoe AND Money is greater than 200.

enter image description here

Now, I know I can execute 3 queries, first to check if the actual user has Jondoe as Username, then check if he has enough Money and if these results are true, then UPDATE (+1) a ticket finally.

I'm learning SQL and i'm working over a mssql database, what's the proper way to do such a conditional query/update? Can I avoid using that many queries?

I'm also working with laravel framework, I don't know if it comes with any "tool" to accomplish what I want.

Thanks in advance

Write CASE condition for one column in the Query

I have a query in which, I want to apply CASE condition. This is my query:

Select 
    a.mkey, a.party_name, a.doc_no Inward_No, 
    c.type_desc Doc_Type, a.ref_no, 
    convert(varchar(25),a.ref_date,103) Ref_date,
    a.Inward_amt, b.first_name + ' ' + b.last_name ToUser --- here
from 
    inward_doc_tracking_hdr a
inner join 
    user_mst b on a.To_User = b.mkey
inner join 
    type_mst_a c on a.doc_type = c.master_mkey  
                 and a.mkey =227423

What I want is: if I get ToUser as NULL then I want to take Last_To_User in place of that.

How to do this in SQL Server?

mercredi 29 juin 2016

SQL Server, split column values for every 10 strings

Need to split the column Reference values for every 10 characters and need to show it for every row ID

I have data like this

ID       Reference
1        405123  ap41502   ag067156
2        a450912   d109456
3        4a4122   g567412  ol09123  pl212671 et61789
4        6t3450   41234a3   01a459014

Required Result:

ID  Reference
1   405123  ap
1   41502   ag
1   067156
2   a450912   
2   d109456
3   4a4122   g
3   567412  ol
3   09123  pl2
3   12671 et61
3   789
4   6t3450   4
4   1234a3   0
4   1a459014

Error restoring SQL Server 2005 db to a 2012 instance - Statistics 'colid' is dependent on column 'colid'

We're upgrading from a SQL Server 2005 instance to SQL Server 2014. Because SQL Server 2014 doesn't play with SQL Server 2005, I'm using an instance of 2012 as an interim to bring the compatibility level up to where SQL Server 2014 will play with it.

Have a small database with only 1 table but a load of views and stored procedures that, upon restoring to SQL Server 2012, is throwing the error:

System.Data.SQLClient.SQLError: The statistics 'colid' is dependent on column 'colid'.

I ran DBCC on it and no errors were indicated. Did an Update Statistics on the only table.

MS SQL: Filter datastream to first value every 15 minutes

I would like to apply a filter to filter the data to 15 minutes, with only 1 row for every 15 minutes returned.

I have 2 tables data, each table contains 2 columns: "Tijd" as timestamp, "Kanaal 1" as float. A new row is added to both tables based on the frequency of the program (Table 1) or a external trigger (Table 2).

My current code works on the first table

select [Tijd], [Kanaal 1] 
FROM Table_Metingen 
WHERE datepart(mi,tijd) % 15 = 0

Table 1: (regulary updated)

Tijd                | Kanaal 1
2016-06-27 00:00:00 | 53
2016-06-27 00:01:00 | 53
2016-06-27 00:02:00 | 53
2016-06-27 00:03:00 | 53
2016-06-27 00:04:00 | 53
2016-06-27 00:05:00 | 53
2016-06-27 00:06:00 | 53
2016-06-27 00:07:00 | 53

Tabel 2: (updated by an external trigger)

Tijd                | Kanaal 1
2016-06-27 00:00:01 | 53
2016-06-27 00:01:02 | 53
2016-06-27 00:01:04 | 53
2016-06-27 00:01:10 | 53
2016-06-27 00:02:04 | 53
2016-06-27 00:05:03 | 53
2016-06-27 00:06:02 | 53
2016-06-27 00:10:01 | 53

Output of current code would be as following: Table 1: (regulary updated)

Tijd                | Kanaal 1
2016-06-27 00:00:00 | 53
2016-06-27 00:15:00 | 53
2016-06-27 00:30:00 | 53
2016-06-27 00:45:00 | 53
2016-06-27 01:00:00 | 53
2016-06-27 01:15:00 | 53
2016-06-27 01:30:00 | 53
2016-06-27 01:45:00 | 53

Tabel 2: (updated by an external trigger)

Tijd                | Kanaal 1
2016-06-27 00:00:01 | 53
2016-06-27 00:15:02 | 53
2016-06-27 00:30:04 | 53
2016-06-27 00:45:00 | 53
2016-06-27 00:45:2  | 53 < Extra row, not needed
2016-06-27 01:00:01 | 53
2016-06-27 01:15:03 | 53
2016-06-27 01:30:01 | 53
2016-06-27 01:30:05 | 53 < Extra row, not needed
2016-06-27 01:45:02 | 53

What table a record came from and if more than one table

I have 4 tables (Table1 through Table4) and column CODE in each table. I use a UNION ALL to identify where they come from

select  distinct CODE, 'Table1'  from Table1 where TABLE1_EFF_STARt >= '01/01/2014'
union all
select  distinct CODE, 'Table2' from Table2 where TABLE2_EFF_STARt >= '01/01/2014'
union all
select  distinct CODE, 'Table3' from Table3 where TABLE3_EFF_STARt >= '01/01/2014'
union all
select  distinct CODE, 'Table4' from Table4 where TABLE4_EFF_STARt >= '01/01/2014' 

Sometimes the same CODE can be in more than one table, and I want to identify and return the result in a below table form. When code in more than one table I want to flag it as Y in the Multisource column.

CODE    Table1  Table2  Table3  Table4  Multisource

12345   Y       N       N       N       N
34233   Y       Y       N       N       Y
45345   Y       N       N       N       N
23417   Y       N       Y       N       Y
45346   Y       N       N       N       Y

Referencing another table in T-SQL not working

I've been running a query on a large number of servers, and on just three of them (SQL2000, SQL2005 AND SQL2008) the query fails. I've boiled it down to referencing a table in another DB.

SELECT * FROM MASTER.dbo.syslogins AS syslogins

Which works on 99% of the servers, but on the three gives:

Invalid object name 'MASTER.dbo.syslogins'

If I switch to the master DB and run

SELECT * FROM dbo.syslogins AS syslogins

Then it works. I've also checked I have permissions by running

SELECT IS_SRVROLEMEMBER('sysadmin');

Which returns a 1. So why does referencing the MASTER.dbo.syslogins table fail?

mardi 28 juin 2016

In SQL Server, is there a way to determine the values of the parameters passed to an executing stored procedure

One way to determine the executing stored procedure is to use "dynamic management" methods, like so:

SELECT sqlText.Text, req.* FROM sys.dm_exec_requests req
OUTER APPLY sys.dm_exec_sql_text(req.sql_handle) AS sqltext

However, this only displays the text of the stored procedure's create statement. e.g.:

CREATE PROCEDURE IMaProcedure @id int AS SELECT * FROM AllTheThings Where id = @id

Ideally I'd like to see what the parameters were for the running procedure that are causing it to run so long for the particular set of offending parameters.

Is there a way to do that?

Create a Cursor and loop all users data

I have a Stored procedure which gives me records like below.

SC

Now what I want is. I want to create a CURSOR for the SP which loops for every user and fetch the records.

Below is my SP.

ALTER PROCEDURE GET_INWARD_REMINDER_REPORT
            AS
            BEGIN

                      Select distinct
                          U.first_name + ' ' + U.last_name UserName,
                    TH.*, 
                CASE 
                        WHEN TL.U_datetime < DATEADD(d, -5, GETDATE()) 
                        THEN M.Reporting_To
                            ELSE NULL 
                            END Reporting_1
                        from inward_doc_tracking_trl TL
                        INNER JOIN inward_doc_tracking_hdr TH
                            ON TH.mkey = TL.ref_mkey
                        INNER JOIN user_mst U
                            ON TH.User_Id = U.mkey
                        INNER JOIN emp_mst M
                            ON M.mkey = U.employee_mkey
                        where TL.NStatus_flag NOT IN (5,14)
                        and TL.U_datetime < DATEADD(d, -3, GETDATE())
            END
GO

Kindly let me know how to do this.

Create Stored procedure for setting reminder for document created

I want to create a Stored procedure for the

  1. documents whose NStatusFlag should not be equal to 5 and 14

AND

also it should send Reminder to the respective user if the Document is with them for more than 3 days and if it is for more than 5 days then it should send it to its senior also

The date should be calculated with the U_datetime of the table and with the SYSTEM date from the system.

My NStatusFlag suggest which all documents are opened.

I tried below.

ALTER PROCEDURE GET_INWARD_REMINDER_REPORT
AS
BEGIN
    Select * from inward_doc_tracking_trl 
        where NStatus_flag <> 5
        and NStatus_flag <> 14
END
GO

SO I got all the documents which are opened, like below

Image

But I am stuck how to get the all user by comparing with the date and send the reminders.

Also, I will get the Name of the USer with which the document is assigned from the inward_doc_tracking_hdr table.

NOTE inward_doc_tracking_hdr table mkey is related to ref_mkey from the inward_doc_tracking_trl table.

kindly help me out.

lundi 27 juin 2016

Return rows where field contains non alpha-numeric characters

I am trying to extract all rows which contain a non alpha numeric character at it's most literal except allowing space. Any punctuation, brackets - square and round, currency symbols etc.

I have tried to adapt the advice as given here Return sql rows where field contains ONLY non-alphanumeric characters however using not LIKE '%[a-z0-9]%' returns rows with a space. Fine. I amend the regex to be not LIKE '%[a-z0-9 ]%' and I now have zero rows returned. What am I doing wrong?

samedi 25 juin 2016

SQL: creating Dynamic SQL getting scalar error on XML node

I'm getting 'Must declare the scalar variable "@model_look_xml"' error. When creating a dynamic query.

This executes fine:

SELECT * FROM model where (model_height between 0.00 and 80.00 and model_id
in (Select distinct assn.assn_model_id From model_look Inner Join
model_skill On model_look.model_look_model_id =
model_skill.model_skill_model_id Inner Join
assn On assn.assn_model_id = model_skill.model_skill_model_id
Where assn.assn_office = 34 and model_skill_skill_id =  12 and  exists
select 1 from  @model_look_xml.nodes('/root/id')as result(node) where
node.value('(.)[1]', 'int') = model_look_look_id))

When I try to break it up dynamically, I'm not sure how to handle the nodes.

This works fine:

SET @SQL = N'SELECT * FROM model where '
SET @SQL = @SQL + N'(model_height between '
SET @SQL = @SQL + cast(@low_height as varchar(50)) 
SET @SQL = @SQL + ' and '
SET @SQL = @SQL + cast(@top_height as varchar(50))
SET @SQL = @SQL + N' and model_id in (Select distinct assn.assn_model_id From '
SET @SQL = @SQL + N'model_look Inner Join
    model_skill On model_look.model_look_model_id =
    model_skill.model_skill_model_id Inner Join
    assn On assn.assn_model_id = model_skill.model_skill_model_id
    Where assn.assn_office = '+ cast(@assn_office as varchar(50)) +'
    and   model_skill_skill_id =  '+ cast(@model_skill_skill_id as varchar(50) ) --+'))'
SET @SQL = @SQL + N' and  exists(select 1 from '

Until I get to this line, not sure how to handle it. If I was only going to do this once I would have found a different way, but I'm going to have 6 optional parameters(possible lists) coming in.

 SET @SQL = @SQL + N'@model_look_xml.nodes(''/root/id'')as result(node) where node.value(''(.)[1]'', ''int'') = model_look_look_id))'

vendredi 24 juin 2016

SQL Server - Sync 200 tables

I have a SQL Server 2005 server that contains a DB of about 200 tables. I need to nightly sync those tables to other DB's on the same server. The sync'ing would always be one way. I'm hoping to avoid having a INSERT, UPDATE & DELETE statement for every table. Is there a good way to do this?

connect to sql server 2005 remotly

I install sqlexpress 2005 on remote machine and I can connect to that with machinename\sqlexpress locally . but i cant connect to that engine remotely.

I did below action but problem still exist :

1- turn off firewall on both side

2- enable tcpip protocol and set tcp port(IPALL) to 1433 and disable 'Listen All'(because if tcp is enabled and 'Listen All' is enabled at the same time, sqlengine is going to stop and I have to disable Listen All in order to start engine )

3- server allow for remote connection box is checked 4- sqlbrowser is started

5- I use mix mode athentication

and also when i try to connect to engine I see packets in Wireshark with dst port=1434 that belong to sqlbrowser service.

at the end I cant connect to sqlengine locally with this servername : 127.0.0.1\SQLEXPRESS but machinename\sqlexpress or .\sqlexpress are OK thank you for your attention

jeudi 23 juin 2016

Input date value in sql

I want to update my promotion table, like :

update [promotion]

set DateStart='2016.06.24 08:00:00', 

DateEnd='2017.07.10 10:00:00',

TimeStart1='2016.06.24 18:00:00',

TimeEnd1='2017.10.10 12:00:00',

TimeStart2='2016.10.02 411:00:00',

TimeEnd2='2017.12.25 15:00:00'

where PromotionName='40%Off';


And it result with error message bellow :

Msg 242, Level 16, State 3, Line 1
The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
The statement has been terminated.

Can we input date in sql ?

mercredi 22 juin 2016

SQL Server 2005 Split email text field to a view table

Having read through multiple, very good, high powered options for splitting delimited text columns I have come to the conclusion that I need assistance dumbing it down for a relative newbie to SQL Server.

Explanation of the issue: I am at the mercy of the previous programmer. Sigh. We have an (1) email column entry for shipments in our existing unmodifiable system. When we have more than one receiver we place multiple emails in the column delimited by commas (BAD design !!!).

A shipper has edited their program to accept multiple key columns and manually split the email column into separate email columns. Other shipper's programs can't be changed. I am using MY view table for concatenated key columns to feed the data to the secondary programs - which works for all instances except when the email column contains more than one email address.

Explanation of (a) Resolution:

I need the original email column intact in the view table and (5) more columns added to my view table with a possible email address parsed from the original column. This needs to work for the existing rows and any future rows. I assume that one AlterTable or AlterView statement will do the trick.

TIA++

mardi 21 juin 2016

Get text instead of ID

I have a query in which I am getting Department_Id as 812 its Integer value. I have referenced this ID with text in another table which is

select type_desc from type_mst_a where master_mkey = 812

and my query is

select convert(varchar(15),doc_Date,103)Doc_Dates, 
         case outward_Type when 'N' then 'None' when 'P' then 'Private' when 'C' then 'Confidential' 
         end [Type], convert(varchar(15),ref_date,103) Ref_dates, convert(varchar(15),Updated_Bill_Date,103)Updated_Bill_Dates ,
         convert(varchar(15), Due_Date,103)Due_dates,* from view_A_Inward_Doc_Tracking_Hdr 
         where delete_flag='N'  and mkey= 227381

How to get the value of that ID ?

dimanche 19 juin 2016

How can i efficiently genereate reports in MS SQL 2005

I am quit new to programming and trying my best to learn. I search the internet to find a solution for my situation but could not find any. So i hope there is someone who can help me. I am gonna try to explain as clear as possible my situation.

I am trying to generate (sales) reports. The application (c#) is combining mssql2005. I can generate reports but it is not efficient and when there is big data it takes ages to generate.

I have the next tables which i use for generating reports (i'll filter the important columns)

table VAT

  • -int Id
  • -int Value

table invoice

  • -int Ticketnumber
  • -Datetime Date
  • -nvarchar(50) SellerId

table articleline

  • -int linenumber
  • -int Ticketnumber
  • -decimal(18,3) Amount
  • -decimal(18,2) Price
  • -nvarchar(50) Item
  • -decimal(18,2) Discount
  • -int VatId

table transaction

  • -int linenumber
  • -int Ticketnumber
  • -nvarchar(20) PayMethod (Card, Cash or Mix)
  • -decimal(18,2) TicketSum (Sum of invoice)
  • -decimal(18,2) Received (received amount from customer)
  • -decimal(18,2) ExtraMoney (can withdraw extra money if paying card)
  • -decimal(18,2) DiscountAmount (sum of discount of the invoice)
  • -decimal(18,2) MixPaymentCard (if payed mix, sum here of card payment)
  • -decimal(18,2) MixPaymentCash (if payed mix, sum here of cash payment)
  • -nvarchar SumRounding (if rounding is active f.e 3,99 --> 4,00 or 3,97 --> 3,95 rounding options can be All, OnlyCash or None)

How I start

What i am doing is running code below. I found this code online and editted for my needs which works for me. I think I know how it works. It is looping though my VAT's and generates for every VAT a small report

DECLARE @RowsToProcess int DECLARE @CurrentRow int DECLARE @SelectVATID int DECLARE @SelectVATValue int

DECLARE @table1 TABLE (RowID int not null primary key identity(1,1), Id int, Value int ) INSERT into @table1 (Id, value) SELECT Id, Value FROM VAT SET @RowsToProcess=@@ROWCOUNT

SET @CurrentRow=0 WHILE @CurrentRow<@RowsToProcess BEGIN SET @CurrentRow=@CurrentRow+1 SELECT @SelectVATId=Id, @SelectVATValue = Value FROM @table1 WHERE RowID=@CurrentRow

SELECT Articleline.Ticketnumber, sum((Articleline.Price * Articleline.Amount) - IsNull(Articleline.Discount,0)) AS Revenue, Transaction.PayMethod, Transaction.SumRounding, Articleline.VAT

FROM Articleline INNER JOIN Invoice ON Articleline.Ticketnumber = Invoice.Ticketnumber INNER JOIN Transaction ON Transaction.Ticketnumber = Invoice.Ticketnumber WHERE (Invoice.Date between @dateStart and @dateEnd) AND Articleline.VAT = @SelectVATID group by Articleline.Ticketnumber, Transaction.PayMethod, Transaction.SumRounfing, ArtiCleline.VAT END

Here below an example of the result. I get multiple results

result 1 (VAT 0%)

Ticketnumber     Revenue       PayMethod      Rounding       VAT
.                ..            ..             ..             ..

result 2 (VAT 6%)

Ticketnumber     Revenue       PayMethod      Rounding       VAT
1                17.25000      Cash           All            2
2                1.55000       Card           All            2
3                3.25000       Cash           All            2

result 3 (VAT 21%)

Ticketnumber     Revenue       PayMethod      Rounding       VAT
3                7.89000       Cash           All            3
4                4.95000       Card           All            3
5                18.95000      Mix            All            3

After I get these result tables from mssql I do a loop in C# to SUM the revenue. I do it this way so can calculate the VAT sum's in C# because this way i get them seperated.

After this I do another mssql query

select * from Transaction INNER JOIN Invoice ON Transaction.Ticketnumber = Invoice.Ticketnumber WHERE (Invoice.Date between @DateStart and @DateEnd)

this will give me the next result

Result transaction

TicketNr   Method   Sum   Received   ExtraMony   Discount   MixCard   MixCash
1          Cash     17.25 20.00      0           0          0         0
2          Card     1.55  1.55       0           0          0         0
3          Cash     11.14 20.00      0           0          0         0
4          Card     4.95  14.95      10.00       0          0         0
5          Mix      18.95 18.95      0           0          8.95      10.00

From here I loop though the table to get the sum's for cash payments, card payments, discounts etc.

From here I show the numbers on the screen. When the data is not that much it goes smooth and is generated instantly. But when there are lots of data it can take long time to finish which is a pain in the but. I hope there is someone who can help me. Maybe i can calculate all of this in 1 sql query or something.

Assign Inserted Identity column to other table

I am going to insert the table from temporary table

SELECT D.ID,D.NAME,D.VALUE,T.TOM_ID
 * INTO #TEMP_TBL  
FROM DOM D INNER JOIN TOM T
ON D.ID =T.ID

NOW I will insert this temp table records to another table COM(THIS TABLE HAVE IDENTITY FILED OF COM_ID)

INSERT INTO COM ( ID,NAME,VALUE ) FROM SELECT ID ,NAME, VALUE FROM #TEMP_TBL Now my requirement is I need to get inserted records identity values(com_id) and have to refer to other table

INSERT INTO TYPE
(
TYPE_ID,COM_ID,NAME,TOM_ID)
SELECT ID,COM_ID(FROM IDENTITY INSERTED IN ABOVE TABLE)NAME,TOM_ID FROM #TEMP_TBL
 ) 

There is more than one record get inserted in every table.How to i find the inserted identity column and assigned this to other.

samedi 18 juin 2016

How to using variable on looping mssql

I have some varchar variable like this:

@var1='data a', 
@var2='data b',
@var3='data c', 
...,
@varn='data n'

i want to insert these variable on looping script.

DECLARE @counter INT
SET @counter = 1
WHILE(@counter <= n)
BEGIN
update [table] set [header] where data=[@var1-n]
set @counter=@counter+1
END
GO

how to make @var1 - @varn can use with loop on [@var1-n]?

vendredi 17 juin 2016

PHP seems to add in backslashes when strings are concatenated

I am creating a query where I am passing in parameters and when the string query is concatenated, there are backslashes which are added and this makes the query not run worthy.

 $searchQuery = "Select * from  <table_name> where Department like
 '".$department. "' and Purchaser_Name like '%".$purchaser. "%' and
 Vendor_Name like '%".$vendor. "%' and User_Name like '%".$requester.
 "%' and PS_Account like '%".$psaccount. "%' ;";

this above string is converted

"Select * from  [dbo].[Unicard_Transactions] where Department like  \'%staff%\'  and Purchaser_Name like \'%mordica%\' and Vendor_Name like \'%crucial%\' and User_Name like \'%reeves%\' and PS_Account like \'%739000%\' "

Would like to know how I can go about creating a search string without the slashes.

Same Column check in Sql Insertion

I have table dom having these two columns(FLAT_AMOUNT,FLAT_PERCENTAGE)

So I just going to insert the table dom

Insert into Dom
   select
     CASE WHEN FLAT_PERCENTAGE = 0 THEN 0 END AS FLAT_AMOUNT
     CASE WHEN PN_TYPE = 'AD' THEN 0
     WHEN PN_TYPE = 'OD' THEN 1
     WHEN PN_TYPE IN('SB','FP','AM','G') THEN 2
     ELSE 0
  END AS FLAT_PERCENTAGE

I hope you got my point.Is there a possible way to check same column values in the table to make insert for other column?

jeudi 16 juin 2016

How find duplicates in a table with no primary key or ID field?

I've inherited a SQL Server database that has duplicate data in it. I need to find and remove the duplicate rows. But without an id field, I'm not sure how to find the rows.

Normally, I'd compare it with itself using a LEFT JOIN and check that all fields are the same except the ID field would be table1.id <> table2.id, but without that, I don't know how to find duplicates rows and not have it also match on itself.

TABLE:

productId int not null,
categoryId int not null,
state varchar(255) not null,
dateDone DATETIME not null

SAMPLE DATA

1, 3, "started", "2016-06-15 04:23:12.000"
2, 3, "started", "2016-06-15 04:21:12.000"
1, 3, "started", "2016-06-15 04:23:12.000"
1, 3, "done", "2016-06-15 04:23:12.000"

In that sample, only rows 1 and 3 are duplicates.

How do I find duplicates?

SQL multiple counts from multiple tables

I have the following tables (“All_Countries” & “_Sent”) and need to get the result as presented in the “Result” table. What I want is to count all “SubscriberKeys” and the total “SendIDs” connected to these SubscriberKeys, grouped by “Source” – just as in the “Result” table. I managed to achieve this (I think) by using the query below but I’m not sure if I did it the wrong way. Isn’t there a better (and more efficient) way of doing this with just one select statement and without the extra sub query? I use SQL server 2005.

All_Countries

-------------------------------
SubscriberKey*    | Source
-------------------------------
10001             | Campaign1
10002             | Campaign2
10003             | Campaign1

_Sent

-----------------------
SendID*| SubscriberKey*
-----------------------
1      | 10001
2      | 10001
3      | 10002
4      | 10002
5      | 10003
6      | 10003

Result

-----------------------------------------------------
Source*          | SubscriberCount       | SendCount
-----------------------------------------------------
Campaign1        | 2                     | 4
Campaign2        | 1                     | 2


Primary keys = * (e.g where you have a star in the column)

SELECT a.Source, COUNT(a.SubscriberKey) AS Subscribers, 
(SELECT COUNT(b.SubscriberKey) AS Sent FROM _Sent AS b
INNER JOIN All_Countries AS c ON b.SubscriberKey = c.SubscriberKey
WHERE c.Source = a.Source) AS Sent
FROM All_Countries AS a
GROUP BY a.Source

SQL: Difference Between Current Row of StartTime Column And Previous Row of EndTime Column

I have a Table in which there are multiple columns but I need to find the Difference Between Current Row of StartTime Column And Previous Row of EndTime Column.

Example is the Following output.

Batch Number    Start Time  End Time        Difference

100004          8:00:00     8:03:30        
100005          8:05:00     8:07:00         00:01:30
100006          8:08:40     8:15:00         00:01:40
32141           8:18:00     8:22:45         00:03:00
84230           8:25:10     8:33:42         00:02:25
23444           8:40:00     8:43:00         00:06:18
100001          8:50:00     8:52:00         00:07:00            

I am new to SQL and am using SQL SERVER 2008 R2.

Please help me to get the output in Simple Select Query.

mercredi 15 juin 2016

Silent installation of SQL 2014 express edition is not working with the code used for SQL 2005 express edition

My application installer does the silent installation of SQL Express 2005. I am trying with the same code to install SQL Express 2014. Here is the code that i am using.

               string SQLfn = strSQLPath;
                string SQLp = "/qn INSTANCENAME=SQLEXPRESS ADDLOCAL=ALL";
                ProcessStartInfo psiSQL = new ProcessStartInfo(SQLfn, SQLp);
                Process SQLprocess = new Process();
                try
                {
                    SQLprocess = System.Diagnostics.Process.Start(psiSQL);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

I am getting Error code: 0x84B40001.

Error Message: The syntax of argument "/QN" is incorrect. Either the delimiter '=' is mising or there is one or more space characters before delimiter'='. Please use /? to check usage.

Cases i tried:
1. SQL Express 2005 i am not getting this error.
2. SQL Express 2014 normal installation is working fine as well. So only silent installation is creating problem.
3. I have SQL Server 2008 in my machine with instance name SQLSERVER.

I browsed through net and found /QN is one of the command used for silent installation with no UI.

But this error makes me strange.

Mine is a development machine. I have different visual studio versions in machine and SQL Server 2008 R2.

And the reason i stick to code, i successfully ran the same code with SQLExpress 2014 an year (but things got erased from my mind as well.)

Please do suggest, what could be the work around to fix this issue.

Thanks for your support in advance.

Regards, Siva.

How to use user defined table type in function for return?

create type mt as table (a int, b int)

Below function works:

create function fn2()
returns @mt table (a int, b int)
as 
begin 
insert into @mt 
Select 1, 2 
return
end 

Below does not work:

create function fn2()
returns @mt table mt
as 
begin 
insert into @mt 
Select 1, 2 
return
end 

Any comments on how type 'mt' can be used for return type?

SQL 2005 Merging without the MERGE function

I am going to appologise in advance for how this question may come out but i will try and explain my best.

I have managed to produce a result set into a temp table which looks like the below.

col1          col2             col3           col4           col5
1             1                1              1             0
1             1                1              0             1
2             2                2              2             0
2             2                2              0             2

So in effect i would like col4 and col5 to read

col4            col5
1               1
2               2

as i am using sql 2005 i am unable to use a merge.

Please can someone advise what function would be best to use to get my desired out come.

Thank you in advance

Invalid column name importing from XML to SQL

I'm getting an error trying to import a XML file to SQL. The code looks like this:

USE MyDB

declare @xmldata as xml

set @xmldata = (SELECT CONVERT(XML, BulkColumn)AS Bulkcolumn
FROM OPENROWSET (BULK 'FILENAME', SINGLE_BLOB) as X)

INSERT INTO BenCalCopy1(BenefitCalcID, RangeBenID, CalculationID)
SELECT 

BenefitCalcID AS [BenefitCalcID],
RangeBenID AS [RangeBenID],
CalculationID AS [CalculationID]

The error message given is:

Msg 207, Level 16, State 1, Line 11
Invalid column name 'BenefitCalcID'.
Msg 207, Level 16, State 1, Line 12
Invalid column name 'RangeBenID'.
Msg 207, Level 16, State 1, Line 13
Invalid column name 'CalculationID'.
Msg 207, Level 16, State 1, Line 8
Invalid column name 'BenefitCalcID'.

And the XML File is given as:

<row>
  <BenefitCalcID>'intvalue'</BenefitCalcID>
  <RangeBenID>'intvalue'</RangeBenID>
  <CalculationID>'intvalue'</CalculationID>
</row>

count with IF condition in SQL

how i will add IF condition ,if for a single student there are five subejct data has been inserted then i want to restrict it for six data....as i have done this in below query but i cannot ad IF with this,,,

SELECT Count(Student_ID) as 'StudentCount' 
FROM tbCourseSemOne
where Student_ID=1 
Having Count(Student_ID) < 6 and Count(Student_ID) > 0;

mardi 14 juin 2016

Best way to detect sql server congestion/slow response

We're building a server monitor. We would like to keep stats about our SQL Server (among many other servers and hardware) and after, let's say a month, be able to detect at what times during the week our sql servers are slower.

We're facing some timeout issues and would like to detect the best times to run our report generation tools (that do heavy queries). That would be when the servers are not too busy.

Is there a stored procedure we could execute to retrieve those stats? Or monitor it let's say every minute? So we could store the values and get stats from those metrics after a month or two?

Show projects on the basis of login user

I have a query which brings Project Name and mkey. The query is below

select  
    distinct
    comp.company_name as 'Company',EMP.emp_name as 'Employee',
     EMP.emp_card_no as 'Card_No',
     EMP.mkey as 'Mkey',
    isnull(hub.type_desc,'--NA--') as 'HUB_Name'
    ,isnull(Program_name,'--NA--') as 'Site',isnull(Project_name,'--NA--') as 'Project'
    from emp_mst EMP
    JOIN emp_mst1 PINFO ON EMP.MKEY=PINFO.MKEY 
    left join company_mst comp on EMP.comp_mkey=comp.mkey and fa_year=2008
    left join type_mst_a b1 on EMP.New_Dept_mkey=b1.master_mkey --and b1.type_code='d11'
    left join type_mst_a c1 on EMP.New_Subdept_mkey=c1.master_mkey-- and c1.type_code='d2'
    left join type_mst_a d1 on EMP.new_design_mkey=d1.master_mkey --and d1.type_code='dm1'
    left join type_mst_a e1 on EMP.ctc_hdr_mkey=e1.Add_IINFo1 and e1.type_code='gr'

    left join type_mst_a f1 on EMP.department_mkey=f1.master_mkey-- and f1.type_code='d1'
    left join type_mst_a g1 on EMP.designation_mkey=g1.master_mkey --and g1.type_code='dm'
    join emp_mst s1 on s1.mkey=EMP.reporting_to
    left join emp_mst s2 on s2.mkey=EMP.reporting_to2
    left join Emp_Address_Trl addr on addr.mkey=emp.mkey 
    left join state_mst as s on addr.state_mkey=s.mkey 
    left join city_mst as c on addr.city_mkey = c.mkey 
    left join view_p_program pg on EMP.project_mkey=pg.mkey 
    left join view_p_project pr on EMP.building_mkey=pr.mkey 
    left join type_mst_a hub on EMP.hub_mkey=hub.master_mkey and hub.type_code='HWH'
    WHERE 
    EMP.STATUS IN ('A','S')

SO what I want is, I want to show the PROJECT NAME of the assigned user on the form.

PROJECT

I want to show on page_load of the page.

<td align="right" class="Header" colspan="1">
            Location : <asp:label ID="lblproject" runat="server" Visible="false" Text='<%#= %>'></asp:label>
        </td>

how to bind the query so that it can show the relevant project name

lundi 13 juin 2016

Alternate way of Exists with Having clause

Hi pls refer the below query

  SELECT PA.PERSON_ID,
   PA.PERSON_ACCOUNT_ID,
   DR.DISBURSEMENT_REQUEST_ID,
   SUM
   (  
        ISNULL(CD.EE_PRE_TAX_AMT,0) + 
        ISNULL(CD.EE_ADDL_PRE_TAX_AMT,0)
   ) AS EE_PRE_TAX_CONTRIB,
   DD.PRE_TAX_AMOUNT AS DISB_DTL_PRE_TAX_AMOUNT,
   SUM
   (     ISNULL(CD.EE_POST_TAX_AMT,0) + 
         ISNULL(CD.EE_ADDL_POST_TAX_AMT,0)
   ) AS EE_POST_TAX_CONTRIB,
   DD.POST_TAX_AMOUNT AS DISB_DTL_POST_TAX_AMOUNT
   FROM SGT_DISBURSEMENT_REQUEST DR
   INNER JOIN SGT_DISBURSEMENT_DETAIL DD ON DR.DISBURSEMENT_REQUEST_ID = DD.DISBURSEMENT_REQUEST_ID 
   INNER JOIN SGT_PERSON_ACCOUNT PA ON PA.PERSON_ACCOUNT_ID = DR.PERSON_ACCOUNT_ID
   INNER JOIN SGT_CONTRIB_DTL CD ON CD.PERSON_ACCOUNT_ID = PA.PERSON_ACCOUNT_ID 
   WHERE DR.REQUEST_CATEGORY_VALUE = 'REFD' AND
         DD.DETAIL_CATEGORY_VALUE = 'REFD' AND
         CD.STATUS_VALUE = 'VALD' AND
         CD.POSTED_DATE <= DR.ACCEPTED_TO_PAYROLL_DATE AND
         DR.DISBURSEMENT_STATUS_VALUE <> 'CANL' AND
      EXISTS
        (
            SELECT 1 FROM SGT_DISBURSEMENT_REQUEST SDR1 
            INNER JOIN SGT_DISBURSEMENT_DETAIL SDD1 ON SDD1.DISBURSEMENT_REQUEST_ID = SDR1.DISBURSEMENT_REQUEST_ID
            WHERE SDR1.PERSON_ACCOUNT_ID = DR.PERSON_ACCOUNT_ID and SDD1.DETAIL_CATEGORY_VALUE = DD.DETAIL_CATEGORY_VALUE
            GROUP BY SDR1.PERSON_ACCOUNT_ID 
            HAVING COUNT(*) = 1
        )
   GROUP BY 
        PA.PERSON_ID, PA.PERSON_ACCOUNT_ID, DR.DISBURSEMENT_REQUEST_ID, DD.PRE_TAX_AMOUNT, DD.POST_TAX_AMOUNT

The above query is to retrieve the records whose(SGT_DISBURSEMENT_REQUEST) count is only one. It is working great.But performance wise it didn't took so much of time since we have lakhs of records.

Is there any alternate way to do it.

Index GUI Issues with SSMS 2014 and 2016 when working with SQL 2005

We currently work with all versions of SQL Server from 2005 onwards. To save time I try to do everything in a single version of Management Studio... This also helps if running newer client operating systems like Windows 10 which old client tools aren't compatible with.

Specifically when trying to view the graphical SSMS interface for index properties I get the following error if connected to a SQL 2005 instance.

In object explorer; Database > Table > Indexes > Right Click > Properties

enter image description here

Full error text:

TITLE: Microsoft SQL Server Management Studio

Exception has been thrown by the target of an invocation. (mscorlib)


ADDITIONAL INFORMATION:

Cannot read property IsSparse.This property is not available on SQL Server 2005. (Microsoft.SqlServer.Smo)

For help, click: http://ift.tt/28x4qlg


This also happens in SSMS 2014, but not SSMS 2012.

So my question is; can something be done to work around this issue allowing one version of management studio to be used for all versions of SQL Server from 2005 onwards?

I'm guessing now, but as it works in SSMS 2012 there must be something going on that targets an older version of mscorlib. Maybe because SSMS 2012 uses a VS2010 shell and different .Net framework?

Many thanks in advance for your time.

dimanche 12 juin 2016

Stored procedure giving error while implementing

While implementing the procedure I am getting error as

Msg 156, Level 15, State 1, Procedure GET_USER_REPORT_DATA, Line 19 Incorrect syntax near the keyword 'select'.

Msg 102, Level 15, State 1, Procedure GET_USER_REPORT_DATA, Line 23 Incorrect syntax near ')'.

Here is the procedure

ALTER PROCEDURE [dbo].[GET_USER_REPORT_DATA]
                @From_Date datetime,
                @To_Date datetime

            AS
            BEGIN


                Select * into #GetUserTable
                    from
                        (
                              select distinct a.N_UserMkey, b.mkey,   
                              ISNULL(b.first_name + ' ' , '') + ISNULL(b.last_name,'') NAME
                              from inward_doc_tracking_trl a inner join user_mst b on 
                              a.N_UserMkey = b.mkey 
                              where a.U_datetime between @From_Date and @To_Date    

                                select distinct a.mkey, b.ref_mkey from inward_doc_tracking_hdr a inner join
                                inward_doc_tracking_trl b on
                                a.mkey = b.ref_mkey
                                and a.U_datetime between @From_Date and @To_Date                                                                                      
                        ) as xx   


                    SELECT * FROM #GetUserTable
                    DROP TABLE #GetUserTable

    END 

samedi 11 juin 2016

How to make and update ranking in database c#

I have this query:

Select [col], DENSE_RANK() Over(ORDER BY col DESC)as rank From Table

I have 2 column, x and y. But i want to update data in column x with result of DENSE_RANK(). Honeslty, i don't know how can that's query work, but when i try, that's work.

But when i tried that's query in query builder, will appear a warning "The OVER SQL construct or statement is not supported." . So i need to make ranking of data in column x, then save the result of ranking into column y.

How to run LOOP in a cursor for each user

I have a SP, which gives me two records (2 username) like below

SP loop

Now,

what I want is to loop each user using cursor and display its data from the table for the date which is passed as in the parameter

Below is my SP.

ALTER PROCEDURE GET_USER_REPORT_DATA
        @From_Date datetime,
        @To_Date datetime

    AS
    BEGIN

        Select * into #GetUserTable
            from
                (
                      select distinct a.N_UserMkey, b.mkey,   
                      b.first_name + ' ' + b.last_name NAME from inward_doc_tracking_trl a inner join user_mst b on 
                      a.N_UserMkey = b.mkey 
                      where a.U_datetime between @From_Date and @To_Date                  
                ) as xx     

    DECLARE @N_Usermkey int, @mkey int, @NAME varchar       
        DECLARE UserCursor CURSOR FOR  
            select distinct a.N_UserMkey, b.mkey,   
                      b.first_name + ' ' + b.last_name NAME from inward_doc_tracking_trl a inner join
                      user_mst b on a.N_UserMkey = b.mkey 
                      where a.U_datetime between @From_Date and @To_Date
        OPEN UserCursor

    FETCH NEXT FROM vendor_cursor   
            INTO @N_Usermkey, @mkey, @NAME 

        -- need to run loop for each user

            SELECT * FROM #GetUserTable
                         DROP TABLE #GetUserTable
    END

GO

I am unaware on how to use cursor kindly let me know

Cannot insert NULL values into column 'USERNAME', table 'tempdb.dbo.#temptable error

I have a SP. while executing I am getting error as

Cannot insert the value NULL into column 'USERNAME', table 'tempdb.dbo.#temptable__________________________________________________________________________________________________________0000000002FD'; column does not allow nulls. UPDATE fails. The statement has been terminated.

Below is my SP

ALTER PROCEDURE [dbo].[UserReportData] 
                @As_ONDATE Datetime 

                AS 
            BEGIN 
                    DECLARE @REPORTDATE datetime        
                    DECLARE @USERNAME varchar(110)      

            Select * INTO #temptable
        FROM
                    (
                        select  a.CUser_id, b.User_Id, a.U_datetime
                        as REPORTDATE, b.first_Name + ' '  + b.last_name as USERNAME
                        from inward_doc_tracking_trl a inner join user_mst b
                        on a.CUser_id = b.mkey
                        and a.U_datetime >= @As_ONDATE
                ) as x

DECLARE Cur_1 CURSOR
            FOR SELECT CUser_id, User_Id FROM #temptable

                    OPEN Cur_1
                        DECLARE @CUser_id INT
                        DECLARE @User_Id INT
                        FETCH NEXT FROM Cur_1 
                        INTO @CUser_id, @User_Id

                        WHILE (@@FETCH_STATUS = 0)
            BEGIN

                            SELECT @REPORTDATE = U_datetime FROM inward_doc_tracking_trl                        
                            where  U_datetime >= @As_ONDATE                             



                            UPDATE #temptable
                                SET REPORTDATE = @REPORTDATE,
                                    USERNAME = @USERNAME
                                WHERE CUser_id = @CUser_id
                                AND User_Id = @User_Id  


                FETCH NEXT FROM Cur_1 INTO @CUser_id, @User_Id
                    END
            CLOSE Cur_1
            DEALLOCATE Cur_1


            SELECT * FROM #temptable
                        DROP TABLE #temptable                           
    END

vendredi 10 juin 2016

Stored procedure not returning any data for the date passed

I have a SP, which takes one parameter as DATE. which will return the data for that date from the table.

ALTER PROCEDURE [dbo].[UserReportData] 
                @As_ONDATE Datetime 

                AS 
            BEGIN 
                    DECLARE @REPORTDATE datetime        
                    --DECLARE @OPENING INT      

            Select * INTO #temptable
        FROM
                    (
                        select  a.CUser_id, b.User_Id, a.U_datetime
                        as REPORTDATE
                        from inward_doc_tracking_trl a inner join user_mst b
                        on a.CUser_id = b.mkey
                        and a.U_datetime = @As_ONDATE
                ) as x

DECLARE Cur_1 CURSOR
            FOR SELECT CUser_id, User_Id FROM #temptable

                    OPEN Cur_1
                        DECLARE @CUser_id INT
                        DECLARE @User_Id INT
                        FETCH NEXT FROM Cur_1 
                        INTO @CUser_id, @User_Id

                        WHILE (@@FETCH_STATUS = 0)
            BEGIN

                            SELECT U_datetime FROM inward_doc_tracking_trl                      
                            where  U_datetime = @As_ONDATE                     

                            UPDATE #temptable
                            SET REPORTDATE = @REPORTDATE
                                WHERE CUser_id = @CUser_id
                                AND User_Id = @User_Id
                                and 

                FETCH NEXT FROM Cur_1 INTO @CUser_id, @User_Id
                    END
            CLOSE Cur_1
            DEALLOCATE Cur_1


            SELECT * FROM #temptable
                        DROP TABLE #temptable                           
    END

When I execute the SP, I do not get any rows returned by executing exec UserReportData '20160610'

but in table i have dates. like running below query

SELECT U_datetime FROM inward_doc_tracking_trl  where  u_datetime = '2016-06-10 14:56:11.000'

So, why there is no record shown while executing the SP

Executing the stored procedure causes error

I have a stored procedure in which I want to get the reportdate while executing.

I pass one parameter to the SP for executing it,. I pass it like this

exec UserReportData '10-06-2016'

but I get an error:

The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.

This is my stored procedure:

ALTER PROCEDURE [dbo].[UserReportData] 
    @As_ONDATE Datetime 
AS 
BEGIN 
    DECLARE @REPORTDATE datetime        
    --DECLARE @OPENING INT      

    SELECT * 
    INTO #temptable
    FROM
        (SELECT 
             a.CUser_id, b.User_Id, a.U_datetime AS REPORTDATE
         FROM 
             inward_doc_tracking_trl a, user_mst b
         WHERE
             a.CUser_id = b.mkey
             AND CONVERT(varchar(50), a.U_datetime, 103) = @As_ONDATE) AS x

    DECLARE Cur_1 CURSOR FOR 
        SELECT CUser_id, User_Id 
        FROM #temptable

    OPEN Cur_1

    DECLARE @CUser_id INT
    DECLARE @User_Id INT
                        FETCH NEXT FROM Cur_1 
                        INTO @CUser_id, @User_Id

                        WHILE (@@FETCH_STATUS = 0)
            BEGIN

                            SELECT convert(varchar(50), U_datetime, 103) FROM inward_doc_tracking_trl                       
                            where convert(varchar(50), U_datetime, 103) = @As_ONDATE                     

                            UPDATE #temptable
                            SET REPORTDATE = @REPORTDATE
                                WHERE CUser_id = @CUser_id
                                AND User_Id = @User_Id

                FETCH NEXT FROM Cur_1 INTO @CUser_id, @User_Id
                    END
            CLOSE Cur_1
            DEALLOCATE Cur_1


            SELECT * FROM #temptable
                        DROP TABLE #temptable                           
    END

Kindly help me know what is the cause of the error.

Inserting a XML table into a SQL table

I'm trying to put a XML file into a SQL table. I've successfully gotten the XML file into the SQL server using the following code:

declare @xmldata as xml

set @xmldata = (SELECT CONVERT(XML, BulkColumn)AS Bulkcolumn
FROM OPENROWSET (BULK 'filedestination', SINGLE_BLOB) as X)

and the following snippet of code is where I get an error. I'm aware that I must use an INSERT INTO statement but I'm not sure where I'm going wrong here.

INSERT INTO t1(c1, c2, c3)
SELECT  
c1 AS 'c1',
c2 AS 'c2',
c3 as 'c3'

I'm currently using SQL Server 2005.

Not able to execute the stored procedure

I have table in which my date column value is saved with time also

like this 2016-06-10 14:56:11.000

Now while executing my SP, I pass one parameter as date like this exec UserReportData '06-10-2016' but it is not showing any records. As it has 4 records in the table.

why?

UPDATE

ALTER PROCEDURE [dbo].[UserReportData] 
                @As_ONDATE Datetime 
                AS 
            BEGIN 
    DECLARE @REPORTDATE datetime        
    DECLARE @OPENING INT        

            Select * INTO #temptable
        FROM
                    (select distinct  a.CUser_id, b.User_Id,a.U_datetime as REPORTDATE, b.first_name + ' ' + b.last_name AS USERNAME,
                    0 OPENING,  0 TOTAL_DOCUMENT, 0 INWARD, 0 FIRST_LEVEL_PROCESSING, 0 DATA_ENTRY
                    from inward_doc_tracking_trl a, user_mst b
                    where a.CUser_id = b.mkey
                    and a.U_datetime = CONVERT(varchar(10), @As_ONDATE, 103)
                ) as x

DECLARE Cur_1 CURSOR
            FOR SELECT CUser_id, User_Id FROM #temptable

                    OPEN Cur_1
                        DECLARE @CUser_id INT
                        DECLARE @User_Id INT
                        FETCH NEXT FROM Cur_1 
                        INTO @CUser_id, @User_Id

                        WHILE (@@FETCH_STATUS = 0)
            BEGIN

                SELECT @REPORTDATE  FROM inward_doc_tracking_trl                        
                 where U_datetime = CONVERT(varchar(10), @As_ONDATE, 103)

                            UPDATE #temptable
                            SET REPORTDATE = @REPORTDATE
                            WHERE CUser_id = @CUser_id
                            AND User_Id = @User_Id

                FETCH NEXT FROM Cur_1 INTO @CUser_id, @User_Id
                    END
            CLOSE Cur_1
            DEALLOCATE Cur_1


    SELECT * FROM #temptable
                DROP TABLE #temptable

    END

Not getting proper value in temp table

I have created an SP, which brings me the data from the inward_doc_tracking_trl table.

Here is my SP,

ALTER PROCEDURE [dbo].[UserReportData] 
                @As_ONDATE Datetime 
                AS 
            BEGIN 
    DECLARE @REPORTDATE datetime        
    DECLARE @OPENING INT        

            Select * INTO #temptable
        FROM
                    (select distinct  a.CUser_id, b.User_Id,a.U_datetime as REPORTDATE, b.first_name + ' ' + b.last_name AS USERNAME,
                        0 OPENING,  0 TOTAL_DOCUMENT, 0 INWARD, 0 FIRST_LEVEL_PROCESSING, 0 DATA_ENTRY
                        from inward_doc_tracking_trl a, user_mst b
                        where a.CUser_id = b.mkey
                        and a.U_datetime = @As_ONDATE
                    ) as x

        DECLARE Cur_1 CURSOR
                    FOR SELECT CUser_id, User_Id FROM #temptable

                    OPEN Cur_1
                        DECLARE @CUser_id INT
                        DECLARE @User_Id INT
                        FETCH NEXT FROM Cur_1 
                        INTO @CUser_id, @User_Id

                        WHILE (@@FETCH_STATUS = 0)
            BEGIN

                SELECT @REPORTDATE  FROM inward_doc_tracking_trl                        
                 where U_datetime = @As_ONDATE 

                            UPDATE #temptable
                            SET REPORTDATE = @REPORTDATE
                            WHERE CUser_id = @CUser_id
                            AND User_Id = @User_Id

                FETCH NEXT FROM Cur_1 INTO @CUser_id, @User_Id
                    END
            CLOSE Cur_1
            DEALLOCATE Cur_1


            SELECT * FROM #temptable
            DROP TABLE #temptable

    END



 -- exec UserReportData '2016-06-10' 

So my issue is when I execute the Stored procedure UserReportData with today's date

I get REPORTDATA column as blank. but there is a row in the table for that date.

kindly know where i am going wrong

how i install mssqlcli on my windows 7 machine.

How can I install ms sql client on my windows 7 machine ? Because without this driver error is "Provider cannot be found"

I am using mssql server 2005 on my Win XP, I am fail to install dot net framework 2 on windows 7 client.

jeudi 9 juin 2016

report on daily attendance, door events database

I have table [acc_monitor_log]. Which has raw events stored for employees.

I convert raw logs to basic columns what are needed.

SELECT  convert(char(10), al.[time], 105) [exactdate]
        , convert(char(5), al.[time], 108) [exacttime]
        , u.[Name]
        , u.[lastname]
        , u.[Badgenumber]
        ,[type of entry] = case when al.[state] = 1 then 'Exit' else 'Entry' end 
        ,al.[event_point_name]

  FROM [access].[dbo].[acc_monitor_log] al, [access].[dbo].[USERINFO] u
  where 
 [time] >= '01-06-2016'
 and al.[card_no] = u.[CardNo]
 and u.[Name] <> 'Vizitator'
 and al.[event_point_name] like '%AC-%'

So results are something like this.

exactdate   exacttime   Name    lastname    Badgenumber type of entry   event_point_name
01-06-16    7:57    user1   user1   9   Entry   Floor.5
01-06-16    12:04   user1   user1   9   Exit    Floor.5
01-06-16    13:08   user1   user1   9   Entry   Floor.4
01-06-16    17:27   user1   user1   9   Exit    Floor.4
02-06-16    7:43    user2   user2   10  Entry   Floor.5
02-06-16    12:02   user2   user2   10  Exit    Floor.5
08-06-16    13:01   user2   user2   10  Entry   Floor.5
08-06-16    17:29   user2   user2   10  Exit    Floor.5

I need to find out employees who went out during lunch 12:00 - 13:00 but did not return on the same day. What troubles me that I need to have it covering whole month. If I needed that within a day, I think I wouldn't be stuck with this.

How can I exclude rows from the same day? Ideally I would need list of employees who went out on which day and did not return on that day.

Create Stored procedure with reference to old stored procedure

I have an OLD SP which is working fine as per the requirement. Here is what it looks like.

OLD SP

and the SP is below:-

ALTER PROCEDURE [dbo].[GET_RECORDS_FORDATE]      
                                @From_date Datetime,      
                                @To_date Datetime      

                                AS      
                                BEGIN      
                                CREATE TABLE #temp(      
                                date datetime, Total int,doc_From_To varchar(50),Inward int, First_Level_Transfer int,      
                                Data_Entry_Transfer int,       
                                Second_Level_Transfer int, Outward_Transfer int,      
                                Closed int, Communication_Transfer int, Returned int     
                            )      

                              INSERT INTO #temp      
                              (date, Total,doc_From_To, Inward, First_Level_Transfer,      
                               Data_Entry_Transfer,       
                               Second_Level_Transfer, Outward_Transfer,      
                               Closed, Communication_Transfer, Returned)      
                              SELECT      
                               doc_date, COUNT(*),      
                             (select kk.doc_no FROM inward_doc_tracking_hdr kk where mkey in (select min(mkey) FROM inward_doc_tracking_hdr jj  
                             where jj.doc_date =convert(datetime,aa.doc_date,103) )  )  
                               + ' - '+  
                             (select kk.doc_no FROM inward_doc_tracking_hdr kk where mkey in (select max(mkey) FROM inward_doc_tracking_hdr jj  
                             where jj.doc_date =convert(datetime,aa.doc_date,103) )  )  
                               ,SUM(      
                               CASE      
                                WHEN status_flag in ('6','23') THEN 1 ELSE 0      
                               END)  
                               ,SUM(      
                               CASE      
                                  WHEN status_flag in ('4','26','24','19') THEN 1 ELSE 0      
                               END)  
                               ,SUM(      
                               CASE      
                                  WHEN status_flag in ('15','20') THEN 1 ELSE 0      
                               END),      
                               SUM(      
                               CASE      
                                  WHEN status_flag in ('17','21') THEN 1 ELSE 0      
                               END),      
                               SUM(      
                               CASE      
                                  WHEN status_flag in ('18','27') THEN 1 ELSE 0      
                               END),      
                               SUM(      
                               CASE      
                                  WHEN status_flag='5' THEN 1 ELSE 0      
                               END),      
                               SUM(      
                               CASE      
                                  WHEN status_flag='16' THEN 1 ELSE 0      
                               END),    
                               SUM(      
                               CASE      
                                  WHEN status_flag='14' THEN 1 ELSE 0      
                               END)    
                              FROM inward_doc_tracking_hdr  aa    
                              WHERE doc_date between @From_date and @To_date   
                            --AND status_flag <> '6'      
                              GROUP BY doc_date      

                            END      

            Select * from #temp

So, now what I want is, I want to create a another SP which will have following column as my output and only with one parameter

I am using SQL-server-2005 Please help

How to replace a character in a string using T-SQL

In my table column, i have below sample data

Test1 145,  Area 1
Test2 146,
Test3 145,  Area 2, Plot 10

What i want to achieve is to replace "," in the string but only if it is the last character. If i have more characters after "," then the replace should leave the string as it is.

In the example above, the replace would only work in line 2.

The expected out put would be like below

Test1 145,  Area 1
Test2 146 
Test3 145,  Area 2, Plot 10

In line 2 above, "," has been replaced with empty space.

I have tried this Replace(column1, ', ', '') AS ColName but this replaces the "," in Test1 and Test3.

mercredi 8 juin 2016

Thousand separator to large number in SQL Server 2005

We have a table where we are using a column to store the price of the item. The column size is 17.2 decimal. We need to have both thousand separator and decimal separator in the string. We are currently using this:

SELECT '$' + convert(varchar,cast('2123232322323.21' as money),-1) as Price

But it raises an error if the size exceed 15 digits.

SQL COALESCE modification

I have below code

SELECT @email = COALESCE(@email + ', ', '') + Email
FROM dbo.FTX_ALERTUSER WITH (NOLOCK)
WHERE AlertID = 9017 AND Email IS NOT NULL
--SELECT @email
--jlee_20160106b fixed bug from 20151028 change where Vendoremail not included.
SELECT @email2 = VENDOREMAIL FROM FTX_NCMR_VENDOR_REQUIREMENT WITH(NOLOCK) where VENDORCODE = @param1  and BU = @param2
SELECT @email = @email + ',' + ISNULL(@email2,''' ''')

which is creating string

[ftx_alert_list] 'updateLastRunDT','9017','FTX-Software, Karthik@XYZ.com, ray@XYZ.com, tony@XYZ.com, yen@XYZ.com,' '','FTX_F20160607004'

I want to correct this string like

exec [ftx_alert_list] 'updateLastRunDT','9017','FTX-Software, Karthik@XYZ.com, ray@XYZ.com, tony@XYZ.com, yen@XYZ.com','','FTX_F20160607004'`

The only difference is ,' '', i want ','', after yen@XYZ.com.

Please help.

exec stored procedure with flexible parameter for "select count(*)..." and sending an eMail

i want to write a SP to send an eMail when the select count(*) value is bigger then the value "Menge" This SP should be used fleixble due the Params for more Tables and/or "where criteria"

Unfortunately i get this erorr and iam not able to fix it :(

Msg 245, Level 16, State 1, Procedure sp_eMail_Test3, Line 23 Conversion failed when converting the varchar value 'select count(*) from test where not [sys_completed] is null' to data type int. Blockquote

Can you help me?

My SP:

create PROCEDURE [dbo].[sp_eMail_Test3]
 @recordCount as int = 0, 
 @FileN as varchar(max) =null,
 @DatSubj as varchar(20) =null,
 @DatFile as varchar(20) =null,
 @SQL_Count as varchar(max) =null,

 @MySQL as varchar(max)=null,
 @MyTable as varchar(max)=null,
 @MyWhere as varchar(max)=null,

 @Menge as int = 0,

 @eMail_TO varchar(max) =null,
 @eMail_Subject varchar(max) =null,
 @eMail_Body varchar(max) =null

AS
BEGIN
    SET NOCOUNT ON;     
    set @MySQL = 'select count(*) from ' +@MyTable + ' where ' + @MyWhere 
    set @SQL_Count = @MySQL 
    set @recordCount = convert(int, @SQL_Count ) -- <<--this is the error

    IF (@recordCount > @Menge)  
    begin           
        -- variablen zuweisung
        set @DatSubj =  CONVERT(varCHAR(20),  GETDATE() ,120) --datum fürs subject
        set @DatFile =  replace(convert(varchar, getdate(), 120), ':','_') --datum für filename
        set @FileN ='Eska_Report_' + @DatFile +'.csv' --filename

        EXEC msdb.dbo.sp_send_dbmail
            @body_format = 'HTML',
            @profile_name = 'testmailprofile',
            @recipients = @eMail_TO,         
            @subject =  @eMail_Subject ,
            @Body = @eMail_Body  ,
            @query = 'SET NOCOUNT ON;
                        select * from Test where sys_gueltig = ''Y'' 
                        and not sys_completed is null  ',
         @attach_query_result_as_file = 1       , 
         @query_attachment_filename= @FileN     , 
         @query_result_separator = ';'      ,
         @query_result_no_padding= 1,       
         @exclude_query_output =1,      
         @append_query_error = 1,   
         @query_result_header =1
    end    
END

I call the SP in this way

exec sp_eMail_Test3
    @Menge = 0,
    @eMail_TO = 'testuser@test.xx' ,
    @eMail_Subject = 'test3 ',
    @eMail_Body = 'Hallo, das ist ein Test',
    @MyTable ='test'    ,
    @MyWhere = 'not [sys_completed] is null'

In the future i want to call the SP via ADO conenct in VBA

vendredi 3 juin 2016

Using SQLCMD in Views and stored procedures (SSMS 2005)

I know I can get the results I want by using a Dynamic SQL string but wondered if I could utilise SQLCMD for some of my more complex queries.

I have a situation where I'm running a query on one database that obtains some of its data from a separate database. So far so straightforward!

However, this separate database changes name each year(in this example db_2016). So I have a query like this (but longer and more complex!)

Mycte1 as (
select x,y,z from main_database.dbo.table
 ),
Mycte2 as (
select db_2016.dbo.field1,db_2016.dbo.field2 from 
       db_2016.dbo.another_table
)

Now with SQLCMD I can add

:isvar SourceDatabase db_2016

and the select now becomes

Mycte1 as (
select x,y,z from main_database.dbo.table
 ),
Mycte2 as (
select $(SourceDatabase).dbo.field1,$(SourceDatabase).dbo.field2 from 
       $(SourceDatabase).dbo.another_table
)

So at the end of the year all I need to change is the SourceDatabase field.

This works fine in Management Studio when I use Query>SQLCMD, but how can I achieve this when the SQL is part of a View or Stored Procedure?

jeudi 2 juin 2016

parent child relationship between composite key and foreign key

Sorry I have to post this again because I thought my first post was confusing I need a design suggestion from all you experts

So I have tables as below:

Table 1

( A integer not null , B char(1) not null , C integer not null , D not null , primary key (A, B, C, D) i.e. composite key )

Table 2

( A integer not null , B char(2) not null , C integer not null primary key (A, B, C) composite key )

Table 3

( A integer not null , B char(2) not null , D not null primary key (A, B, D) )

I want to create a relationship between table 1 and 2 and Table 1 and 3.

Table 1 being the parent table and table 2 and 3 being the child table of Table 1. I can easily creat a relationship between table 1 and table 2, but I get an error when I try to create a relationship between 1 and 3 because the foreign key can not be the part of the composite key and it has to be the whole composite key. I would highly appreciate any suggestions.

VBScript and SQL Server 2005 compare current row to previous row

I am dealing with some legacy tech at my new job. Everything is either VBS or VBA and SQL Server 2005 is still running for at least 1 server, and 2008 on another. I can't change the tech I have to work with, so please don't respond with "Just use PowerShell" ... which is all I got from the Microsoft forums.

I need to modify an existing VBScript to iterate through the records of a table and give each page of a document a page number. The page number starts at 1 and resets to 1 every time the location folder changes, as defined by the row's value in the column Path. So I need to compare the current row's Path to the previous row's Path to see if there is a change.

From the specs request:

Use the following structure:

  • Outermost folder = Box field

    • Sub-folder = File Folder field
      • Docs within will each begin at "0000001"
        • Sub-folder = File Folder field
          • Docs within will each begin at "0000001"
    • Sub-folder = File Folder field

      • Docs within will each begin at "0000001"

Here is a very simple but effective Excel script that works, unfortunately I have to use VBScript so a third-party software can run the script:

=IF  "Folder field in this row" = "Folder field in row above"
True = "above column" (beg doc of previous doc) + "pgcount of previous doc"
False = "1"

Here is the existing SQL statement from within the VBScript (Sorry for the naming convention - it is not my choice):

UPDATE tblpage 
SET tblpage.UID = newtable.keyid 
FROM tblpage inner join (SELECT PKEY, '" & prefix & "' + REPLICATE(0, " & padnum & " -
LEN(convert(varchar(" & padnum & "),(" & startnum & " + rank() OVER (ORDER
BY TBLDOC." & sortfield & ") + Page - 2)))) + CONVERT(nvarchar(" & padnum &
"), convert(varchar(" & padnum & "),(" & startnum & " + rank() 
OVER (ORDER BY TBLDOC." & sortfield & ") + Page - 2))) AS keyid 
FROM tblpage 
inner join tbldoc on tblpage.id = tbldoc.id) as newtable ON newtable.pkey = tblpage.pkey;

variables taken from user input in VBScript - explanation

prefix - optional text prefix to the iterative number ie "SET" for "SET0000001"

padnum - number of 0s before iteration begins ie "000000" for "SET0000001"

startnum - starting number for the iteration ie "1" in "SET0000001"

sortfield - which table column to sort by ie a table's UID.

The above SQL does the iteration correctly but doesn't reset on new folder. I have been looking into http://ift.tt/19vQWo7 but I am still quite confused.

My thoughts are that I join just the Path to the newtable based on the row's UID - 1, and then a case statement to compare them. If different, reset the page number. If the same, continue as normal.

Path is found in tblDoc. Look at UID in tblPage for the page numbering structure

Thanks!!

execute storedprocedure with one arg in server side and sql recognizes as two args

i'm currently trying to execute a stored procudure with one argument. the database is SQL Server 2005 and i am calling the sp from C# using OdbcCommand.

OdbcCommand oCmd = new OdbcCommand("{call sp_dominioMaquinas(?)}");
oCmd.Connection = new OdbcConnection(Config.Config.GetConnectionStringSqlConnection());

string psTipoExportarAux = "'" + psTipoExportar + "'";

oCmd.Parameters.Clear();
oCmd.Parameters.Add("@psTipoExportar", OdbcType.VarChar);
oCmd.Parameters["@psTipoExportar"].Value = psTipoExportarAux;

my problem is that my parameter psTipoExportar is a string with a coma (,) in it. (ex: a', 'b) and so sql server recognizes it as two parameters instead of one.

using a tool to see requests to my DB, I can see that my request is beeing misinterpreted (ex: exec sp_dom '''a'', ''b''') as two arguments when I want it to be processed as one.

if anyone could help out, that you

I'm following MSDN

and i've checked this questions here , here and here.

How to conditionally exclude or add columns when calculating row total

I have a stored procedure with a parameter defined like below

    @CategoryNames  NVARCHAR(MAX)

The above parameter gets a comma separated string from the application, for example the value can be like this @StaffCategoryIds=N'Category1,Category2,Category3,Category4,Category5'

Then i have the sample below sql query

SET @sql = @sql + 'TypeId, 
        TypeName, 
        Condition,
        Region, 
        (Category1 + Category2 + Category3 + Category4 + Category5) AS Total INTO ##QueryResults
FROM Table1;'

When computing my Total column in the query above, how can i first check whether a category column (say Category2 or Category5) exists in my @StaffCategoryIds comma separated string before including it in the computation of my Total column?

Eg. if 'Category2' exists in @StaffCategoryIds, then i include it in computation of Total else i exclude it.

Limit script to run only on specific databases

I have databases

DEV_a    TST_a    REAL_a
DEV_b    TST_b    REAL_b
DEV_c    TST_c    REAL_c

These can be on same server or on different server. Now I'm writing a script/transaction that's relevant only for DEV_a, TST_a and REAL_c.

Is there any way I can limit script to run only on those databases?

I thought this might work:

USE [DEV_a]

but that would force it to run only on one database, but I have a list. Is this doable?

Extra question: if it is doable, can I run parts of the script for DEV_a and TST_a but different part of script for REAL_c?

mercredi 1 juin 2016

SQL update for the varchar column

I want to change the string of AttachmentCopyLoc columns from D:\IT\Public\FTX_RobotAlerts\336 to V:\IT\Public\FTX_RobotAlerts\336 only change here is D to V, the remaining string is the same (I don't event want to change that).

How can I do that?

Thanks in advance for your help.

enter image description here