samedi 30 avril 2016

Laptop blocked after executing 'DBCC FREESYSTEMCACHE and DBCC FREEPROCCACHE

I am a newbie in SQL DBA. The background is SQL SERVER 2005 Pack4, running SQL Server Management Studio as an adming with 5 databases inside a single instance.

To sort out corruption with Object Plans, SQL Plans, Bound Trees, I executed DBCC FREEPROCCACHE and 'DBCC FREESYSTEMCACHE' without adding more instructions.

Now my laptop is stucked for yet 2 hours and the mouse & keyboard don't respond anymore.

I found out on other websites that cleaning all the cache should not be done if you don't know what you are doing, and that it will seriously affect performance but it was too late.

Two questions: 1) What should I do with a blocked PC for 2 hours? 2) Will the cache be rebuilt automatically and after some time perform again ? 3) What should I do to recover the performance I had before the caches were deleted?

Thanks in advance.

jeudi 28 avril 2016

Synchronization of tables from DB2 to SQL

I had build a T-SQL, that which will sync the tables from DB2 to SQL.We can run the job for every 15 min to sync tables. This query will fetch only the changes that were made from the last job done. But this is the query that which was applicable when the servers are linked. But I don't know, for some reasons my manager want it to be done by SSIS. How can i reach my requirement of syncing data only by fetching the changes from last job done? Is there anyway to modify my query and run it in execute SQL task in SSIS?

BEGIN
IF OBJECT_ID('tempdb..#ELIG_TEMP') IS NOT NULL
DROP TABLE #ELIG_TEMP
UPDATE OPENQUERY ([DB2], 'select h_last_job_end from ISO21.V_LATEST_JOB_CYCLE where C_job = ''ELIG''') 
SET h_last_job_end = current_timestamp;

select * into  #ELIG_TEMP from OPENQUERY([DB2],
'Select * from ISO21.V_USR_ELIG p
where I_USR in (select secid from natb.pyratab p,
ISO21.V_LATEST_JOB_CYCLE  pr
where datetime <= h_last_job_end 
and datetime > h_cur_job_start
and c_job = ''ELIG'')')
MERGE iso21.USR_ELIG 
USING #ELIG_TEMP AS ELIG_TEMP
ON (USR_ELIG.I_USR = ELIG_TEMP.I_USR AND USR_ELIG.C_UNIV_TYP = ELIG_TEMP.C_UNIV_TYP AND USR_ELIG.C_UNIV = ELIG_TEMP.C_UNIV)
WHEN MATCHED THEN
UPDATE
SET USR_ELIG.C_UNIV_TYP = ELIG_TEMP.C_UNIV_TYP,
USR_ELIG.C_UNIV = ELIG_TEMP.C_UNIV                                         

WHEN NOT MATCHED BY TARGET THEN
INSERT (I_USR,C_UNIV_TYP,C_UNIV)
VALUES (ELIG_TEMP.I_USR,ELIG_TEMP.C_UNIV_TYP,ELIG_TEMP.C_UNIV)

WHEN NOT MATCHED BY SOURCE THEN
DELETE;

UPDATE OPENQUERY ([DB2], 'select h_cur_job_start,h_last_job_end from ISO21.V_LATEST_JOB_CYCLE where C_job = ''ELIG''') 
SET h_cur_job_start = h_last_job_end;
END`

Query to convert exponential number to float in SQL Server

I am using

SELECT CAST('5E-05' AS float) 

result = 0.00005

and it is not working. Help.

http://ift.tt/1SMvNPT

mercredi 27 avril 2016

XML file conversion to database table

I need to convert XML files to tables in Microsoft SQL Server. How do we convert the URLs in XML files to table data?

mardi 26 avril 2016

What is the LOP_INSERT_ROWS and LOP_DELETE_ROWS operation on a View object?

I'm examining the MS SQL Transaction Log for investigating a problem, and found there are a huge amount of LOP_INSERT_ROWS and LOP_DELETE_ROWS operations on a SQL View object within a single "user_transaction" last for over a minute.

I just curious what is the meaning of a LOP_INSERT_ROWS and LOP_DELETE_ROWS operation on a View object? Do they mean the action on creating and dropping a View object?

Thanks.

Retrieving the deleted DATA

How to retrieve the data that was deleted accidentally? I know that we can retrieve the truncated data if that session was not closed(just by simple rollback). As, delete is a logged operation, is the restoring the database is the only option to retrieve the lost data?

SQL Server - 2008 Format vs Convert

I've always used convert for date formatting, see below. As a new SQL user I see that you can also use FORMAT, see below. I realize that convert function converts your data into a string but when date formatting which is best to use?

FORMAT(getdate(), 'MM/dd/yy') AS [MM/DD/YY],
CONVERT(VARCHAR(8), getdate(), 1) AS [MM/DD/YY]

Build dataset that only shows created events

I need to build a dataset that only shows created events that aren't associated with a reschedule event, because the way the system that generates my data works is that for every time a Rescheduled event occurs a Created event is generated. Both of these events have the same date and timestamp.

This code only shows the Created and Rescheduled events:

select * 
        from wingmanapr2016 a
        left join (select a.action_date from Atable a where exists (select event_name from Btable b where b.event_name = 'Created') and a.event_name = 'Rescheduled') b  on b.action_date = a.action_date
        where a.event_name not in ('Allocated', 'Available', 'completed', 'Edited') 
        order by a.action_date, a.account_number

If someone could give an answer ASAP it would be greatly appreciated

lundi 25 avril 2016

Statement of account from transactions SQL

I have a list of transactions in a table for a user which records, the UserID, DateTime, TransactionType and Value. TransactionID is the Primary Key auto increment 1. The TransactionType defines a Deposit (1) or Withdrawal (2) so all values are positive in the table. I am trying to create a statement of account with a running total.

TransactionID    UserID    DateTime           TransactionTypeID    Value
     1            3112     01-04-2016 12:00          1              5.00
     3            3112     01-04-2016 13:00          2              2.00
     5            3112     01-04-2016 13:25          2              1.00
     8            3112     02-04-2016 12:00          1              10.00
     9            3112     02-04-2016 12:35          2              4.00

Basically I want to create a running statement of account query with a Total value to create:

DateTime           TransactionTypeID    Deposit    Withdrawal    Balance
01-04-2016 12:00          1              5.00                     5.00
01-04-2016 13:00          2                          2.00         3.00
01-04-2016 13:25          2                          1.00         2.00
02-04-2016 12:00          1              10.00                   12.00
02-04-2016 12:35          2                          4.00         8.00

I have tried using OUTER APPLY to select the previous transaction but with no prevail in a single query. Any assistance would be appreciated

SELECT 
    [UserID], [DateTime], 
    T.[Value] * 
    (CASE 
        WHEN [TransactionTypeID] IN (1, -- deposit
                                     2 -- withdrawal
                                    )
            THEN -1
            ELSE 1
     END),
    T2.Value AS PrevValue
FROM 
    [Transaction] T
OUTER APPLY 
    (SELECT TOP 1 T2.[Value]
     FROM [Transaction] T2
     WHERE UserID = 3112 
       AND T2.[TransactionID] > T.TransactionID
    ORDER BY T2.TransactionID) AS T2
WHERE 
    T.[UserID] = 3112
ORDER BY 
    T.[TransactionID] DESC

Cannot connect to server

I am using the same SQL authentication since long time in my desktop. Now i am trying to use on new machine, installed management studio in my laptop and trying to connect. I got the following error. Can anyone tell me the possible issue?. enter image description here

dimanche 24 avril 2016

How to get count in output variable using a stored procedure?

SELECT COUNT(*) 
FROM tblRequest 
GROUP BY RequestStatusID

This query return the column having total requests respective status Id.

I want to get total requests count respective to its statusId in output variables using a stored procedure.

This Query return the Column having total requests respective status Id.

I want to get total requests respective to its statusId in a output variable using store procedure. i.e. it return a column like


|NoNameColumn|
|-----------|
21
|-----------|
6
|-----------|
14
|------ ----|

I Want to get each row value in a output variable separately(eg. SET @pending=21, Set @Sent=6, SET Discarded=14 ), using store procedure and vb.net code.

In simple words.. How can i get that row's values in a variable by the sql store procedur?

How can I Do It..?

vendredi 22 avril 2016

Error in CASE keyword while executing the SQL query in SQL Server

I am executing this query in SQL server but do not know, why it is giving error in "CASE" and "IN" keywords. I am really stuck here. Please help me.I will be very thankful to you.Here is my query.

  SELECT [id]
  ,[name]
  SUM(CASE WHEN (SELECT [code] 
                   FROM [Test].[dbo].[testcode] as ts 
                   WHERE ts.id = t.id) IN (1,2,4) 
            then 100 
            else 10 
           end) as "total" 
  FROM [Test].[dbo].[testcode] as t 
  GROUP BY id, name

jeudi 21 avril 2016

SQL Error of Cannot perform an aggregate function on an expression containing an aggregate or a subquery

I was executing this query in SQL but is giving me an error like this "Cannot perform an aggregate function on an expression containing an aggregate or a sub query." Is there anyone who can help me with it. I am really stuck. Thank you Here is my query.

SELECT [id]
      ,[name]
      ,SUM(case 
           when [code] = 1  Then 
           case 
             when exists(select * from [sampletab] where [id] = [id]and [code] = 2) then

                case when exists(select * from [sampletab] where [id] = [id] and [code] = 4) then 100 
                else 100
                end 

               else 100
               end    
           when [code] = 8 then 200
           when code = 2 then 50
           when code = 4 then 20

      end
      ) as "totl"

  FROM [test].[dbo].[sampletab]
  GROUP BY id , name

My data

What is the difference between a primary key and a surrogate key?

I googled a lot, but I did not find the exact straight forward answer with an example.

Any example for this would be more helpful.

mercredi 20 avril 2016

SQL Server 2005 - View with linked server vs Query with linked server

  • Server1 - Main reporting server
  • Server2 - Other reporting server

I have a linked server setup between Server1 and Server2.

Server1 has a view that runs a query with multiple joins to gather data from Server2.

When I execute the view on Server1 for year to date data, it takes 5 minutes to run.

When I execute the query on Server1 outside of the view, the query takes 2 minutes.

I've also took the query and built a stored procedure, but that also ran in 5 minutes.

Why is there such a difference between running through a view and running just the query?

Eloquent with common table expressions?

Given Larvel 5.2 and a SQL Server 2005 database. I have query something like this:

declare @mapping_table table(id int, name varchar(255), mapping_value varchar(255))

insert into @mapping_table values (1, 'foo', 'A1')
insert into @mapping_table values (2, 'bar', 'A1')
insert into @mapping_table values (3, 'baz', 'A2')

select distinct(lookup_field) 
from production_table
where lookup_field not in (
  select name
  from @mapping_table 
)

When I run this using Eloquent like so: DB::connection('sqlsrv')->select($query) I get the error The active result for the query contains no fields.

Background: I'm creating an app that ensures certain queries result in a valid result set for reporting purposes. Mostly these ara data mappings for free test input to a defined list of options. If a new free text entry is found in the production a query should mention the unmapped value(s) so I can add them to the defined table.

I have no writing access on the production database, only read. Creating stored procedures is not an option due to this limitation. When I copy the query to SQL Server Management Studio it works like charm. I'm guessing this is because SSMS internally seperates the results and Eloquent doesn't.

How can I get a query like the given one get to work with Eloquent?

mardi 19 avril 2016

ADODB.Recordset error '800a0e78' Operation is not allowed when the object is closed

I know this is probably a duplicate of another question but i've searched all over and tried everything but it still seems to be giving me the same error of.We recently migrated from SQL SERVER 2005 to 2008 .After migration We are facing this Problem.I am using classic ASP,SQL and HTML.

Below is My SQL SERVER 2008 PROCEDURE. I noticed one strange thing after migration that in my procedure there are red under lines for temproary table and warning "invalid object " .But when I ran this procedure Manually it return me 6 records

USE [Fastrack] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO

 ALTER PROCEDURE [dbo].[SP_ASH_WEB_S] @GMID VARCHAR(10), @DIR_YR CHAR(4)
 AS

SET NOCOUNT ON

SELECT DIV_MGR_ID,
       '' DMGR_LST_NM,
       MGR_ID,
       ' ' MGR_LST_NM,
       SUM(REV_ASG) TOT_ASG,
       SUM(REV_HDL) TOT_SVC,
       SUM(REV_SLD) CORE_TOT_SLD
       INTO #S_GM_AUDIT
       FROM
       RPT_ASH
       WHERE
       DIV_MGR_ID = @GMID
       GROUP BY
       DIV_MGR_ID,
       MGR_ID

        UPDATE #S_GM_AUDIT
        SET DMGR_LST_NM = D.LST_NM,
        MGR_LST_NM = M.LST_NM
        FROM #S_GM_AUDIT A, ASM M, DSM D
       WHERE A.MGR_ID = M.MGR_ID AND
       A.DIV_MGR_ID = D.DIV_MGR_ID AND
       M.AFF_CD = 'S' AND D.AFF_CD = 'S'

       BACKUP LOG FASTRACK TO DISK='NUL:'

       SELECT * FROM #S_GM_AUDIT

       DROP TABLE #S_GM_AUDIT

Below is the ASP code which is calling this procedure and giving error on line While NOT ors.EOF

<% Option Explicit                                                      
Dim DbObj, SQL, oRs, intRowColor, FNM, GMID, DIR_YR, AFF_CD, YEAR_IND   
FNM = Request.QueryString("FNM")                                        
GMID = Request.QueryString("GMID")                                      
DIR_YR = Request.QueryString("DIR_YR")                                  
AFF_CD = Request.QueryString("AFF")                                     
YEAR_IND = Request.QueryString("YEAR_IND")                              
%>                                                                      
<% Server.ScriptTimeout = 300 %>                                        
<head>                                                                  
<meta NAME="GENERATOR" Content="Microsoft Visual Studio 6.0">           
</head>                                                                 
<%                                                                      
 IF AFF_CD = "P" THEN                                                    
   IF YEAR_IND = "N" THEN                                                
    SQL = "SP_CEO_N_GMGR_CUS_AUDIT_WEB_P '" & GMID & "', '" & DIR_YR & "
  ELSE                                                                  
    SQL = "SP_GMGR_CUS_AUDIT_WEB_P '" & GMID & "', '" & DIR_YR & "'"    
  END IF                                                                
END IF                                                                  
OpenConnection()                                                        
Set oRs = DbObj.Execute(SQL)                                            
 %>                                                                      
 <form method="get">                                                     
 <table BORDER="0" WIDTH="100%" cellpadding="0" cellspacing="0">         
 <%                                                                      
 dim totasg,totsvc,coretotsld,grandtotasg,grandtotsvc,grandcoretotsld    
 WHILE NOT oRs.EOF  
 totasg = oRs.Fields("tot_asg")
 totsvc = oRs.Fields("tot_svc")
 coretotsld = oRs.Fields("core_tot_sld")
 grandtotasg = grandtotasg + totasg
 grandtotsvc = grandtotsvc + totsvc
 grandcoretotsld = grandcoretotsld + coretotsld
 if intRowColor = "0" then 
 intRowColor = "1"                                                     

After Trigger effect in SQL Server 2005 transactional publication

On publisher table P1 we have after trigger on last_update_time column which is fired when any data is updated. On subscriber table S1 we have an insert trigger to audit all the data changes into audit table SA1 . When any data is changed on P1 2 records are inserted into SA1. 1) The data change. 2) update last_date_time data which is the result of after trigger on P1. How can I manage to audit only one record on SA1 for any change on P1 including last_update_time column.

SQL - advice on grouping

SQL Server 2005. I am not after a coded answer here (although it would be nice). I'm really after advice on the best way forward to get the result I need. I have some knowledge of pivot/unpivot/cte//rownumber and dynamic queries but cannot get my head around this particular problem! An example of the data follows. Note: The occurrence of type,location,name and description can be none to many.

drop table #temp
create table #temp
(
event int,
type varchar(20),
locations varchar(20),
name varchar(30),
description varchar(50)
)
insert into #temp values (1,'support','r1','fred','desc 1')
insert into #temp values (1,'support','r1','fred','desc 2')
insert into #temp values (1,'support','r1','fred','desc 3')

insert into #temp values (1,'support','r1','jim','desc 1')
insert into #temp values (1,'support','r1','jim','desc 2')
insert into #temp values (1,'support','r1','jim','desc 3')

insert into #temp values (1,'support','r2','fred','desc 1')
insert into #temp values (1,'support','r2','fred','desc 2')
insert into #temp values (1,'support','r2','fred','desc 3')

insert into #temp values (1,'support','r2','jim','desc 1')
insert into #temp values (1,'support','r2','jim','desc 2')
insert into #temp values (1,'support','r2','jim','desc 3')

insert into #temp values (1,'work','r1','fred','desc 1')
insert into #temp values (1,'work','r1','fred','desc 2')
insert into #temp values (1,'work','r1','fred','desc 3')

insert into #temp values (1,'work','r1','jim','desc 1')
insert into #temp values (1,'work','r1','jim','desc 2')
insert into #temp values (1,'work','r1','jim','desc 3')

insert into #temp values (1,'work','r2','fred','desc 1')
insert into #temp values (1,'work','r2','fred','desc 2')
insert into #temp values (1,'work','r2','fred','desc 3')

insert into #temp values (1,'work','r2','jim','desc 1')
insert into #temp values (1,'work','r2','jim','desc 2')
insert into #temp values (1,'work','r2','jim','desc 3')

select * from #temp

The result I am after is this ..

1,support;work,r1;r2,fred;jim,desc1;desc2;desc3

Why does checking if temp table exists when "CONCAT_NULL_YIELDS_NULL" is set to ON doesn't work?

SET CONCAT_NULL_YIELDS_NULL OFF;  

IF OBJECT_ID ('tempdb..##QueryResults') IS NOT NULL
    DROP TABLE ##QueryResults;

Why is it that if i set set CONCAT_NULL_YIELDS_NULL to off as shown above and temp table ##QueryResults exists, it is successfully dropped but if i set it to ON, then temp table is not dropped even when it exists?

dimanche 17 avril 2016

The foreign key constraint failed when import from excel

I want to import data from excel files to SqlServer2005, but I found the foreign key constraint and triggers all failed during this pcocess, how to solve this problem?

samedi 16 avril 2016

Add Values to dropdownlist on the basis of SQL Query

I have a dropdownlist whose values are binded by a query which is

select emp_card_no, emp_name + '-' + cast(emp_card_no as varchar)+ '(' + datename(MM,a.dt_of_leave) 
 + ' - ' + cast(year(a.dt_of_leave)as varchar)+')' emp_name from emp_mst a where month(a.dt_of_leave) 
  >= month(getdate())-1  and  year(a.dt_of_leave)= case when            month(getdate())=1 then year(getdate())-1 
 else year(getdate()) end order by emp_name 

whose results look something like this.

SQL output

Now what I want is, in Emp_name column, I want to add text as PROCESS OR PENDING after (April - 2016) on the basis of query which is below

select emp_mkey, * from emp_mon_day
where emp_mkey = 312
 and month = 4
 and year = 2016

If query returns any result then PROCESS otherwise PENDING.

NOTE

1st query column Emp_card_no is the Emp_mkey in emp_mon_day table.

Also see the code for binding dropdownlist

protected void funfillEmployee()
{
    DataTable DtCombo = new DataTable();
    string strdate = System.DateTime.Now.ToString("dd/MM/yyyy");

    DtCombo = ObjPriDal.ExecuteDataTable("select emp_card_no, emp_name + '-' + cast(emp_card_no as varchar)+ '(' + datename(MM,a.dt_of_leave)  + ' - ' + cast(year(a.dt_of_leave)as varchar)+')' emp_name  " +
                         "  from emp_mst a where month(a.dt_of_leave) >= month(getdate())-1  and  year(a.dt_of_leave)= case " +
                         "   when  month(getdate())=1 then year(getdate())-1 else year(getdate()) end order by emp_name ");

    cmbEmp_Name.DataTextField = "emp_name";
    cmbEmp_Name.DataValueField = "emp_card_no";
    cmbEmp_Name.DataSource = DtCombo;
    cmbEmp_Name.DataBind();
    cmbEmp_Name.Items.Insert(0, new ListItem("--Select--", "0"));
    DtCombo.Clear();
}

Let me know how to do that.

I am using SQL-server-2005

vendredi 15 avril 2016

How to convert/cast column data type in concatenated SQL query string

i have the following variables defined in my stored procedure

@StartDate  DateTime,
@EndDate    DateTime,

I'm setting the sql to be executed dynamically, so when constructing the query where clause i have the below line.

SET @sql = @sql + ' AND (convert(datetime, R.ReportDate, 121) >= ' + @StartDate + 'AND  convert(datetime, R.ReportDate, 121) <=' + @EndDate +')' 

When i execute the stored procedure, the line above throws the error below

Conversion failed when converting datetime from character string.

If i change the variable datatype to NVARCHAR(MAX), the procedure executes successfully but then returns no rows because the date comparison/matching fails.

ReportDate column is of datatype datetime and has data in this format 2014-06-01 00:00:00.000

As you can see i have tried converting the column when constructing my query but that isn't working.

jeudi 14 avril 2016

Error message Conversion failed when converting datetime from character string

ALTER  PROCEDURE [dbo].[TEST_01]       
 (
    @StartDate  DateTime,
    @EndDate    DateTime
 )
AS      
BEGIN      
  SET NOCOUNT ON;  
  Declare @sql as nvarchar(MAX);
  SET @sql = @sql + ';WITH CTE_ItemDetails
            MAX(D.Name) as Name,
            SUM(ISNULL(DT.col1, 0)) AS col1,
            SUM(ISNULL(DT.col2, 0)) AS col2,
            SUM(ISNULL(DT.col3, 0)) AS col3,
            GROUPING(D.ItemType) AS ItemTypeGrouping
        FROM Items D
            INNER JOIN Details DT ON DT.ItemId = D.ItemId
            INNER JOIN Report R ON R.ReportId = DT.ReportId
            where 1=1'
        SET @sql = @sql + ' AND (R.ReportDate >= ' + @StartDate + 'AND  R.ReportDate <=' + @EndDate +')' 
        SET @sql = @sql + 'SELECT col1, col2, col3 FROM CTE_ItemDetails'
        EXECUTE (@sql)  
END

I have a stored procedure that is similar to the T-SQL code above. (Note that i have removed lots of code that i feel isn't relevant to the error i'm getting) I'm getting the below error when i execute it.

Conversion failed when converting datetime from character string.

My parameters have values in below format

exec TEST_01 @StartDate=N'4/1/2016 12:00:00 AM',@EndDate=N'4/30/2016 12:00:00 AM'

It looks like the trouble is in the way i'm dynamically setting the SQL statement at line below

SET @sql = @sql + ' AND (R.ReportDate >= ' + @StartDate + 'AND  R.ReportDate <=' + @EndDate +')' 

What is the best date formatting i can apply to avoid the error.

Syncing date in sql to current/present date

I have a table LeaveApplication which is used to store the leave applications of employees considering their start and end date of a certain leave. How do i ensure that the from date doesn't consider any previous dates(it is pointless to apply for a leave in April 2016 which had to be taken in January 2016) i hope im clear...any help is appreciated..thank you in advance

SQL query error not working

I have written the sql query but I am getting error as

Incorrect syntax near 'company_name'.

I am using SQL server 2005

SELECT top 1 month(a.dt_of_leave)MONTH,
year(a.dt_of_leave)YEAR FROM emp_mst a WHERE MONTH(a.dt_of_leave) >= MONTH(getdate())-1
 AND YEAR(a.dt_of_leave)= CASE WHEN MONTH(getdate())=1 THEN YEAR(getdate())-1 ELSE YEAR(getdate()) company_name 'COMPANY NAME',
                                                                                    Deputed_Company_Name 'DEPUTED COMPANY NAME' emp_card_no 'EMP CODE',
                                                                                                                                            emp_name 'EMPLOYEE NAME',
                                                                                                                                                     LWP,
                                                                                                                                                     '' Remarks,
                                                                                                                                                        Adj_Days Gain_Loss_LOP_Days,
                                                                                                                                                        VAL_DAY LOP_Days_Desc,
                                                                                                                                                        MONTH,
                                                                                                                                                        YEAR
 FROM XXACL_EMP_INFO_LWP_OTDAYS_HRS_V WHERE emp_type='C'
  AND MONTH = '3'
 AND YEAR = '2016'
 AND emp_card_no IN(312,
                 1250,
                 362)

mercredi 13 avril 2016

Driver JDBC error : no sqljdbc_auth

I have a Java app connected with SQL server 2005 . when launching i have the error : avr. 13, 2016 9:37:05 AM com.microsoft.sqlserver.jdbc.AuthenticationJNI AVERTISSEMENT: Failed to load the sqljdbc_auth.dll cause : no sqljdbc_auth in java.library.path

SQL Statement Two Column Value Return Single Column Value

Please suggest best way to construct sql statement thanks a lot!

example

mardi 12 avril 2016

snapshot Replication from 2005 Enterprise edition to 2014 standard edition article issues

I want configure snapshot replication from 2005 enterprise to 2014 standard,but I am getting following article issue

Indexed views are supported only in the Enterprise Edition of Microsoft SQL Server 2000 or later. You have published one or more indexed view articles that create an indexed view at the Subscriber. For SQL Server Subscribers, only those running the Enterprise Edition of SQL Server 2000 or later will be able to subscribe to this publication.

lundi 11 avril 2016

Count when there are 6 or more unique occurrences in a column then in a new column have a string that identifies it

I have a table with patients, their services, date of services, ect... If a patient has 6+ unique services in a month then in my select statement I want a new column to have the word "Full Month" in it.

vendredi 8 avril 2016

SqlBulkCopy is not inserting rows in same order from the .net DataTable to Sql table in Sql Server

objDataTable=ConversionClass.ConvertToDataTable(strFilePath,"tbl_transactonData", ",");       String strConnectionString =ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;

        SqlBulkCopy bulkCopy = new SqlBulkCopy(strConnectionString);
        bulkCopy.DestinationTableName = "tbl_AllTransactiondata";
        try
        {
            bulkCopy.WriteToServer(objDataTable);
        }
        catch (Exception ex)
        {

        }
        finally
        {
            bulkCopy.Close();
        }

I need to transfer value from datatable to Sql Table using SqlBulkCopy. But SqlBulkCopy is not inserting rows in proper order .Please suggest solution for the same.

jeudi 7 avril 2016

Left join ON not null columns can't select not null column

Each table has a column RECNUM. They are (decimal(28,0), not null). That is where I am doing my join. I want to select the column DESC in CAUNIT. It is (varchar(28,0), not null). When I run my query I get:

Msg 156, Level 15, State 1, Line 1 Incorrect syntax near the keyword 'DESC'. Below is my query:

SELECT CDCLSVC.UNIT_ID,CAUNIT.DESC
FROM CDCLSVC
LEFT JOIN CAUNIT
ON CDCLSVC.RECNUM = CAUNIT.RECNUM

cannot drop the view 'XXX' because it does not exist or you do not have permission

We migrated our servers from 2005 to 2014, User is able to delete it in the 2005 server But in 2014 we are getting the error as do not have permission or does not exits We have given to same permissions and even he is a system admin.

mercredi 6 avril 2016

Read and split XML repeated tags in sql server

I have this XML

<Flujo>
<nodes>
<Nombre>QWERTY</Nombre>
<NombreProceso>Nodo 2</NombreProceso>
<ProcesoTipo>4</ProcesoTipo>
<SolicitudTipo>1</SolicitudTipo>
<Rol>Ejecutivo de plaza: 1</Rol>
<Rol>Supervisor de creditos: 2</Rol>
<Rol>Supervisor de tesoreria: 2</Rol>
</nodes>
</Flujo>

I can read it but I just get one tag. after that I would like to split each tag to get this

        Rol                   Permiso
 Ejecutivo de Plaza              1
 Supervisor de creditos          2
Supervisor de tesoreria          2

any clue?

Thanks

How to solve cyclic relationship in SQL?

I have table for students , instructors and courses.

  1. Relationship between instructor and course many to many (as instructor can teach many course and course can be tough by many instructors ) I create instructorcourse table to break many to many
  2. Relationship between student and course many to many (as student can register in many courses and course have many students) I create studentcourse table to break many to many
  3. Relationship between student and instructor one to many So l have a problem in cyclic relationship

Substring of Url's on a column in Sql Server 2012

Since I am new to Sql Server, I am trying to take substring of this url in Item Url Column eg: http://ift.tt/1SAeU8e Party Action

I want the Related Party Action from this url. I have tried charindex and substring,but confused with the positioning. Also I want every url in ItemUrl column to be like this.Please help me with the select query.

ORA-01790: expression must have same datatype as corresponding expression

My UnPivot Query is as:

Select BirthDate ,FirstName,Gender, Name From Table1
Union
Select BirthDate, FirstName, Gender, Name From
(Select Name2, FirstName2, BirthDate2, Name3, FirstName3, BirthDate3,
Name4, FirstName4, BirthDate4
From Table2)
UnPivot((BirthDate,FirstName,Gender,Name) for sk in ((BIRTHDATE2,FIRSTNAME2,GENDER2,NAME2) as 2,
                              (BIRTHDATE3,FIRSTNAME3,GENDER3,NAME3) as 3,
                              (BIRTHDATE4,FIRSTNAME4,GENDER4,NAME4) as 4))

And I know that the error is due to BirthDate where in the first expression it is Datetime2(7), I tried CAST or To_Date but of no help.

mardi 5 avril 2016

Msg 241, Level 16, State 1, Line 10

I have linked server of DB2. While i m trying to execute this query in SSMS

UPDATE OPENQUERY (DB2PAVAN, 'select column1 from catalog.table WHERE C_JOB = ''USER''') SET column1 = 'current timestamp';

I am getting error Conversion failed when converting date and/or time from character string.

Can you suggest me some method to resolve it?

Is possible to use PHP 5.5 with SQL server 2005?

Hello currently I work with php 5.5.12 and msqlsrv 2014 so i use php_sqlsrv_55_ts.dll AND php_pdo_sqlsrv_55_ts.dll, But i migrate on one server with msqlserv 2005, You know which dll I need, if is posible ?

Thanks.

Automation and network

Please help me I am working in an organization I manage a server Office automation software is installed on the server Users often encountered this error

ERROR

lundi 4 avril 2016

Table Sync from DB2 to MSSQL

We have a tables in Db2, That which we need to get that table to MS SQL server (only for read), And I want it to be in Sync for every 15min. (one way from DB2 to MS SQL). Can you suggest me a best approach.

Select statement using case when inputting data in new column 'conversion failed'

I have a select statement where I am creating a new column called Program.

Select '' as Program

I want to have my case when statement put in this new column a string where the int from the UNIT_ID column is either 8191, 8192 or 8194.

CASE WHEN UNIT_ID = '8194' THEN 'Hospital'
WHEN UNIT_ID = '8192' THEN 'Clinic'
WHEN UNIT_ID = '8191' THEN 'Outpatient'
ELSE CONVERT(VARCHAR(35), UNIT_ID)
END AS PROGRAM,

My query starts off doing this:

WITH CDCLSVC_1 AS (
           SELECT CDCLSVC.*, CASE WHEN CDBILMOD.PROC_CODE = '' THEN

An later on this:

, CDBILMOD_1 AS (
           SELECT * FROM CDBILMOD
           )
, CDCLIENT_1 AS (
           SELECT * FROM CDCLIENT
           )

So far my query runs but does not input any data into my new Program column

dimanche 3 avril 2016

compounding yearly interest using tsq

I want to create a table as such using sql for compounding interest.

name    rate    principal   year1   year2
A       .5      10          15       22.5
B       .0      10          10       10.0

I am able to create a stored procedure and hardcode it for two years of interest for each name but that means that every additional year I have to add another year. Is there an elegant and efficient way for doing this using procedure(s) or just views?

samedi 2 avril 2016

Trying to add minutes to HH:MM to 00:00 in Char(5) Field

I'm pretty new to SQL, someone has asked me for help and I'm trying to assist; I've installed SQL 2005 because this is the version they are running on.

My task:

They have a table called 'appTime' which is a char(5) type contains many times such as: 12:12 08:15 6:22 etc.

I have to increase the minutes in random increments between 1 minute to 15 minutes, I have no idea how to do it.

I've tried to just randomly move the same number to another field eg: UPDATE SET newTime = AppTime and failed..

I'm not sure how to do it, I'm not sure why the time is even in a char type but I assume their software required it.

Any tips, help, assistance is GREATLY appreciated.

Thank you

CURSOR not looping more than once

I am new to SQL Server stored procedures ... I have written a code which is not looping correctly I believe ...

Note: I am unable to use a Debugger so to debug I have used PRINT commands (old school style)

I am using SQL Server 2005

Code enters into the loop and PRINTs the lines only once - where else their are 29 Totals records to be looped and worked on

PRINT 'check if rows are their or not for Adjusting X flags records Results 5 '

SELECT 
    td_clientcd , td_scripcd, cm_name, td_scripnm, 
    sum(td_bqty) td_qty,
    sum(td_sqty) td_sqty, 
    sum(td_bqty-td_sqty) net 
FROM 
    ##VX, Client_master with (nolock)  
WHERE
    td_clientcd = cm_cd  
    AND td_clientcd = @client_cd 
GROUP BY 
    td_clientcd, cm_name, td_scripcd, td_scripnm 
HAVING
    sum(td_bqty - td_sqty) <> 0 
ORDER BY 
    td_clientcd , td_scripcd  

DECLARE dataX_Cursor CURSOR FOR 
    SELECT  td_clientcd , td_scripcd,cm_name,td_scripnm, sum(td_bqty) td_bqty ,sum(td_sqty) td_sqty, sum(td_bqty-td_sqty) net FROM ##VX,Client_master with (nolock)  where td_clientcd = cm_cd  and  td_clientcd = @client_cd  group by td_clientcd,cm_name,td_scripcd,td_scripnm having sum(td_bqty - td_sqty) <> 0 ORDER BY td_clientcd , td_scripcd  

    OPEN dataX_Cursor

    PRINT 'i am at 144'
    DECLARE @tempSumQty INT -- has the qty of the Lower Side
    DECLARE @tempHigherSideFlag CHAR -- show which is the Higher side Sell (S) or Buy (B)

    FETCH NEXT FROM dataX_Cursor INTO @td_clientcode, @td_scripcode, @cm_name, @td_scripname, @td_buyqty, @td_sellqty, @net

    WHILE @@FETCH_STATUS = 0
    BEGIN
        --Example
            -- select * from ##VX where td_clientcd = '26555   ' and td_scripcd = '532804' and td_bsflag = 'B' and td_flag = 'N' order by td_dt desc,td_stlmnt desc
        -- update ##VX set td_flag = 'X' where td_srno = 308
        PRINT 'I am at 155'
        -- !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

        if @td_buyqty > @td_sellqty
                BEGIN
            SET @tempSumQty = @td_sellqty -- Sets the sum of Lower side Qty
            SET @tempHigherSideFlag = 'B'
        END
        ELSE
                BEGIN
            SET @tempSumQty = @td_buyqty -- Sets the sum of Lower side Qty
            SET @tempHigherSideFlag = 'S'
        END  -- This will get the higher Side Qty

        PRINT @tempSumQty 
        PRINT @tempHigherSideFlag

        IF @td_buyqty = 0 OR @td_sellqty = 0 -- Just update the flag to X
                        BEGIN
                            -- select a single/multiple records and loop through it and see if 
                            PRINT 'in OR Condition of X flags'
                            DECLARE record_Cursor CURSOR FOR  
                            select * from ##VX where td_clientcd = @td_clientcode and td_scripcd = @td_scripcode and td_bsflag = @tempHigherSideFlag and td_flag = 'N' order by td_dt desc,td_stlmnt desc -- gets the records will needs to be marked X, which are from higher side.

                            OPEN record_Cursor

                            Fetch Next From record_Cursor Into @td_companycode ,@td_stlmnt,@td_clientcd , @td_scripcd, @td_dt, @td_srno, @td_bsflag,@td_bqty, @td_sqty, @td_rate, @td_marketrate,@td_flag,@td_scripnm,@td_desc
                            -- looping
                            While @@Fetch_Status = 0 
                                            BEGIN

                                                -- update the old record with a flag of X 
                                                update ##VX set td_flag = 'X'  where td_srno = @td_srno


                                                -- fetch next
                                                Fetch Next From record_Cursor Into @td_companycode ,@td_stlmnt,@td_clientcd , @td_scripcd, @td_dt, @td_srno, @td_bsflag,@td_bqty, @td_sqty, @td_rate, @td_marketrate,@td_flag,@td_scripnm,@td_desc
                                            END 

                            --Close record_Cursor
                            --Deallocate record_Cursor

            END -- End of Fetch

            -- if need to adjust the records with an insert and a update

            IF @td_buyqty <> 0 AND @td_sellqty <> 0 -- Adjust the record with an insert and update the flag to X
                    BEGIN
                        -- select a single/multiple records and loop through it and see if 
                        PRINT 'in AND Condition of X flags'
                        DECLARE record_Cursor CURSOR FOR  
                        select * from ##VX where td_clientcd = @td_clientcode and td_scripcd = @td_scripcode and td_bsflag = @tempHigherSideFlag and td_flag = 'N' order by td_dt desc,td_stlmnt desc -- gets the records will needs to be marked X, which are from higher side.

                        OPEN record_Cursor

                        Fetch Next From record_Cursor Into @td_companycode ,@td_stlmnt,@td_clientcd , @td_scripcd, @td_dt, @td_srno, @td_bsflag,@td_bqty, @td_sqty, @td_rate, @td_marketrate,@td_flag,@td_scripnm,@td_desc
                        -- looping
                        While @@Fetch_Status = 0 
                        BEGIN
                                                DECLARE @CurrentRowQty INT
                                        --  PRINT 'i am at 198 ' + CONVERT( VARCHAR(2), @tempHigherSideFlag )
                                                            IF @tempHigherSideFlag = 'S'
                                                                    BEGIN
                                                                        SET @CurrentRowQty = @td_sqty
                                                                    END
                                                            ELSE IF @tempHigherSideFlag = 'B'
                                                                        BEGIN
                                                                            SET @CurrentRowQty = @td_bqty
                                                                        END

                                                IF @tempSumQty > @CurrentRowQty
                                                                BEGIN 
                                                                    SET @tempSumQty = @tempSumQty - @CurrentRowQty
                                                                END
                                                ELSE
                                                        BEGIN
                                                        --  PRINT 'i am at 213 ' + CONVERT( VARCHAR(2), @tempHigherSideFlag )
                                                            IF @tempHigherSideFlag = 'S'
                                                                    BEGIN
                                                                        SET @td_sqty = @td_sqty - @tempSumQty
                                                                        insert into ##VX select td_companycode ,td_stlmnt,td_clientcd , td_scripcd, td_dt, td_bsflag, td_bqty, @tempSumQty, td_rate, td_marketrate,td_flag,td_scripnm,'' from ##VX where td_srno = @td_srno
                                                                        update ##VX set td_flag = 'X' ,td_sqty = @td_sqty where td_srno = @td_srno

                                                                    END
                                                            ELSE -- IF @tempHigherSideFlag = 'B'
                                                                    BEGIN
                                                                        SET @td_bqty = @td_bqty - @tempSumQty
                                                                        insert into ##VX select td_companycode ,td_stlmnt,td_clientcd , td_scripcd, td_dt, td_bsflag, @tempSumQty, td_sqty, td_rate, td_marketrate,td_flag,td_scripnm,'' from ##VX where td_srno = @td_srno
                                                                        update ##VX set td_flag = 'X' ,td_bqty = @td_bqty where td_srno = @td_srno
                                                                    END 
                                                        END -- end of else
                                -- fetch next
                                Fetch Next From record_Cursor Into @td_companycode ,@td_stlmnt,@td_clientcd , @td_scripcd, @td_dt, @td_srno, @td_bsflag,@td_bqty, @td_sqty, @td_rate, @td_marketrate,@td_flag,@td_scripnm,@td_desc

                            END 
                    --Close record_Cursor
                    --Deallocate record_Cursor  

                        END

                --  FETCH NEXT FROM dataX_Cursor INTO @td_clientcode, @td_scripcode, @cm_name, @td_scripname, @td_buyqty, @td_sellqty, @net

                END -- End of Fetch

and finally I

Deallocate record_Cursor
Close dataX_Cursor
Deallocate dataX_Cursor

vendredi 1 avril 2016

how to use output inserted.* into table variable while doing Update

/* I am trying the Output inserted for the first time and not able to understand the Error Message :- Insert Error: Column name or number of supplied values does not match table definition.

Goal: I have a huge claim table with many accounts. I want to update a value to 1 in a few accounts and be able to display the updates.

--SO, I create a @TEMP_tbl with the accounts that I want to update */

DECLARE @TEMP_tbl TABLE ( SORIGCREDITORREFNO VARCHAR(30) ,BCLAIMONHOLD INT )

INSERT INTO @TEMP_tbl (SORIGCREDITORREFNO,BCLAIMONHOLD) VALUES ( '1234',0 )

-- writing my update statement

DECLARE @MYVAR TABLE ( SORIGCREDITORREFNO VARCHAR(30),BCLAIMONHOLD INT)

UPDATE CLAIM SET BCLAIMONHOLD = 1 OUTPUT INSERTED.* INTO @MYVAR WHERE SORIGCREDITORREFNO IN ( SELECT SORIGCREDITORREFNO FROM @TEMP_tbl )

SELECT * FROM @MYVAR
-- want to look at my updates

/* Msg 213, Level 16, State 1, Line 16 Insert Error: Column name or number of supplied values does not match table definition. */