Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I am trying to execute my whole stored procedure as a string since I have to make the condition dynamic.
Here is my code:
```
CREATE PROCEDURE SP1
(@VoucherType varchar(10),
@ProductID bigint,
@BrandID bigint)
AS
BEGIN
DECLARE @Condition as varchar(300)
SET @Condition=' WHERE VoucherType=@VoucherType '
IF (@Pro... | Just do it without a dynamic SQL:
```
SELECT * FROM Products WHERE VoucherType=@VoucherType AND
(@ProductID=-1 OR ProductID=@ProductID)
AND
(@BrandID=-1 OR BrandID=@BrandID)
``` | If the logic is as you describe, you can do this without dynamic SQL - just using the parameters directly in the where clause by using a comparison with your default values for each parameter (essentially making that part of the where clause a no-op if the values are at the value you use to signal for "don't filter").
... | Using varchar parameter in exec() | [
"",
"sql",
"sql-server",
"stored-procedures",
"parameter-passing",
""
] |
I have a database that is used to record patient information for a small clinic. We use MS SQL Server 2008 as the backend. The patient table contains the following columns:
```
Id int identity(1,1),
FamilyName varchar(30),
FirstName varchar (20),
DOB datetime,
AddressLine1 varchar (50),
AddressLine2 varchar (50), ... | This will output every row which has a duplicate, based on firstname and lastname
```
SELECT DISTINCT t1.*
FROM Table AS t1
INNER JOIN Table AS t2
ON t1.firstname = t2.firstname
AND t1.lastname = t2.lastname
AND t1.id <> t2.id
``` | ```
WITH CTE
AS
(
SELECT Id, FamilyName, FirstName ,DOB
ROW_NUMBER() OVER(PARTITION BY FamilyName, FirstName ,DOB ORDER BY Id) AS DuplicateCount
FROM PatientTable
)
select * from CTE where DuplicateCount > 1
``` | Listing duplicated records using T SQL | [
"",
"sql",
"sql-server",
"database",
"sql-server-2008",
""
] |
Let's say I have a User which has a status and the user's status can be 'active', 'suspended' or 'inactive'.
Now, when creating the database, I was wondering... would it be better to have a column with the string value (with an enum type, or rule applied) so it's easier to both query and know the current user status o... | On most systems it makes little or no difference to performance. Personally I'd use a short string for clarity and join that to a table with more detail as you suggest.
```
create table intLookup
(
pk integer primary key,
value varchar(20) not null
)
insert into intLookup (pk, value) values
(1,'value 1'),
(2,'value 2'... | I think, as a whole, everyone has hit on important components of the answer to your question. However, they all have good points which should be taken together, rather than separately.
1. As logixologist mentioned, a healthy amount of Normalization is generally considered to increase performance. However, in contrast ... | Is it better to have int joins instead of string columns? | [
"",
"sql",
"database-design",
"database-normalization",
""
] |
I am getting an error when attempting to execue a dynamic sql string in MS Access (I am using VBA to write the code).
Error:
> Run-time error '3075':
> Syntax error (missing operator) in query expression "11/8/2013' FROM tbl\_sample'.
Here is my code:
```
Sub UpdateAsOfDate()
Dim AsOfDate As String
AsOfDat... | Get rid of `& "FROM tbl_sample " _`. A from clause isn't valid in your update statement. | You really should be using a parameterized query because
* they're safer,
* you don't have to mess with delimiters for date and text values,
* you don't have to worry about escaping quotes within text values, and
* they handle dates properly so your code doesn't mangle dates on machines set to `dd-mm-yyyy` format.
In... | error when executing a dynamic sql string | [
"",
"sql",
"ms-access",
"vba",
""
] |
Suppose I have a dataset as
```
----------------------
col1 | col2 | col3 |
----------------------
a b 3
c d 2
----------------------
```
Now Is there a way in SQL to select
```
----------------------
colx | coly | colz |
----------------------
a b 1
a b 2
a ... | ```
SELECT DISTINCT t.col1 AS colx, t.col2 AS coly, level AS colz
FROM tablee t
CONNECT BY level <= t.col3
ORDER BY t.col1, t.col2, level
```
fiddle: <http://sqlfiddle.com/#!4/01f5b/12> | Please try:
```
with T (colx , coly , colz , mxcol3) as
(
select col1, col2, 1 col3, max(col3) over (partition by col1, col2) mxcol3
from YourTab
union all
select colx , coly , colz +1 colz , mxcol3
from T
where colz +1<=mxcol3
)
select
colx, coly, colz
From T
order by colx, coly, colz;
``` | Select repeated data based on column value | [
"",
"sql",
"oracle",
"iteration",
"calculated-columns",
"repeat",
""
] |
Is there any way by which we can lock only single row of the table (IN SQL SERVER 2008)
I am trying something like this
```
BEGIN TRAN
select TOP 1 from [TableName] with (ROWLOCK,UPDLOCK)
COMMIT
```
But seems like SQL server is ignoring ROWLOCK and acquiring IU lock on page and IX on Table.
Your help will be appr... | With UPDLOCK hint, you are requesting an UPDATE lock, that's why your SELECT is stuck waiting for previous transaction to complete.
You should specify HOLDLOCK but not UPDLOCK:
```
select TOP 1 * from t1 with (ROWLOCK, HOLDLOCK)
```
This will keep a shared lock and let other transaction select data, but not update it... | ```
update Production.Location with (ROWLOCK)
set CostRate = 100.00
where LocationID = 1
```
Use rowlock when you want to update that records. | How to lock single row only for update | [
"",
"sql",
"sql-server",
""
] |
I am looking to use a regular expression to capture the last value in a string. I have copied an example of the data I am looking to parse. I am using oracle syntax.
Example Data:
```
||CULTURE|D0799|D0799HTT|
||CULTURE|D0799|D0799HTT||
```
I am looking to strip out the last value before the last set of pipes:
```
... | Consider the following Regex...
```
(?<=\|)[\w\d]*?(?=\|*$)
```
Good Luck! | You can try this:
```
select rtrim(regexp_substr('||CULTURE|D0799|D0799HTT||',
'[[:alnum:]]+\|+$'), '|')
from dual;
```
Or like this:
```
select regexp_replace('||CULTURE|D0799|D0799HTT||',
'(^|.*\|)([[:alnum:]]+)\|+$', '\2')
from dual;
```
[Here is a sqlfiddle demo](http... | Using Regular Expression Oracle | [
"",
"sql",
"regex",
"oracle",
""
] |
I am trying to get this query to return a record for each year instead of returning a single record for everything in the table.
```
SELECT
JAN
, FEB
, MAR
, APR
, MAY
, JUN
, JUL
, AUG
, SEP
, OCT
, NOV
, [DEC]
,JAN + FEB + MAR + APR + MAY + JUN + JUL + AUG + SEP +... | This will solve, for example, all of the months in 2011, 2012 and 2013, with far less repetitive code.
```
DECLARE @years TABLE(y INT);
INSERT @years SELECT 2011 UNION ALL SELECT 2012 UNION ALL SELECT 2013;
;WITH m(m) AS
(
SELECT TOP (12) ROW_NUMBER() OVER (ORDER BY [object_id]) - 1
FROM sys.all_objects ORDER B... | perhaps :
GROUP BY YEAR(dt\_updated) | Return a record for each year | [
"",
"sql",
"t-sql",
"date",
"sql-server-2005",
""
] |
Say I have a query with several joins across three tables:
```
SELECT
main_data.id,
main_data.dt,
main_data.seq_num,
main_data.sale_amt,
main_data.sale_cd,
promo.promo_cd,
payment.card,
payment.priority
FROM
main_data
INNER JOIN promo
ON promo.id = main_data.id
AND main_data... | You could try this. The row\_number function groups the items in the PAYMENT table by sale\_cd, then orders the entries by priority asc. Thus, row\_num = '1' should give you the lowest value for priority grouped by sale\_cd.
```
WITH CTE AS (CARD, PRIORITY, SALE_CD, ROW_NUM)
AS
(
SELECT CARD
, PRIORITY
... | You have mentioned as main attributes give duplicates, so I have assumed these to be GROUP BY columns
```
WITH A AS
(
SELECT
main_data.id,
main_data.dt,
main_data.seq_num,
main_data.sale_amt,
main_data.sale_cd,
promo.promo_cd,
payment.card,
payment.priority
, ROW_NUMBER() OVER(PARTI... | SQL to retrieve only the minimum value in query with multiple joins | [
"",
"sql",
"sql-server",
""
] |
i want to select set of records in SQL Server table.
In SQL Server, I can do this:
```
select TOP 40,60 *
from sometable
order by name
```
I want to get the 40th to the 60th rows.
Thank you. | i did that like this query
```
WITH temp AS
( SELECT *, ROW_NUMBER() OVER (ORDER BY name) AS 'RowNumber'
FROM sometable
)
SELECT * FROM temp WHERE RowNumber BETWEEN 40 AND 60
```
Thank you for all comment. | LIMIT exists in Oracle but with different arguments, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1):
```
SELECT * FROM sometbl Order by name LIMIT 40,100; # Retrieve rows 41-100
```
Or you c... | Get some set of records in table in SQL Server | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
""
] |
i have one field which contain data like `4563******3245`. when i execute my sql query it is inserted successfully. but in mysql database it is showing only `4563`
my sql query is:
```
insert into mytable ('myfield') values ('4563******3245');
```
Can any one tell me where is the problem.
thank you. | ```
insert into mytable ('myfield') values ('4563******3245');
```
it is working fine
make sure your column type should be varchar | You can't store text in a column of a number data type. You have to change your data type to `char(14)`.
```
ALTER TABLE your_table MODIFY myfield CHAR(14);
``` | How to insert * symbol in mysql using php | [
"",
"mysql",
"sql",
""
] |
I'm trying to create a script for basic database and login/user creation for SqlServer
When i run my script I get many errors like:
> Must declare the scalar variable "@varname"
when the variable is used in an `EXEC` statement for the second time during the script execution.
```
declare
@dbname nvarchar(50) ,
... | Thanks to [Raj](https://stackoverflow.com/questions/19950982/must-declare-the-scalar-variable-varname-in-database-creation-script#comment-29693253) and [Vaibhav Parmar](https://stackoverflow.com/questions/19950982/must-declare-the-scalar-variable-varname-in-database-creation-script#comment-29693778) comments I changed ... | The GO Statement tells the query analyzer that a batch is complete.
<http://technet.microsoft.com/en-us/library/ms188037.aspx>
Therefore, the declared variable that are set are out of scope by the time the dynamic code is executed.
If you truly want this in a transaction, then wrap it with **BEGIN TRY/END TRY** in t... | Must declare the scalar variable "@varname" in database creation script | [
"",
"sql",
"sql-server",
"t-sql",
"execute",
"variable-declaration",
""
] |
```
SELECT CASE WHEN age IS NULL THEN 'Unspecified'
WHEN age < 18 THEN '<18'
WHEN age >= 18 AND age <= 24 THEN '18-24'
WHEN age >= 25 AND age <= 30 THEN '25-30'
WHEN age >= 31 AND age <= 40 THEN '31-40'
WHEN age > 40 THEN '>40'
... | You need a table of agebands to populate the result for entries that have no matching rows. This can be done through an actual table, or dynamically generated with a subquery like this:
```
SELECT a.ageband, IFNULL(t.agecount, 0)
FROM (
-- ORIGINAL QUERY
SELECT
CASE
WHEN age IS NULL THEN 'Unspecified'
... | I haven't tested it, but this should work.
```
SELECT ageband, cnt FROM (
SELECT '<18' as ageband, COUNT(*) as cnt FROMT table WHERE age < 18
UNION ALL
SELECT '18-24' as ageband, COUNT(*) as cnt FROMT table WHERE age >= 18 AND age <= 24
UNION ALL
SELECT '25-30' as ageband, COUNT(*) as cnt FROMT table WHERE a... | MySQL CASE WHEN THEN empty case values | [
"",
"mysql",
"sql",
"case",
""
] |
I have a .CSV import that I will be performing a series of Transformations on.
The first Transformation that I need to do is to merge two City Columns into 1 column.
The data that I have looks like this.
```
| City1 | City2 |
|Wichita| |
| |Houston|
| |Chicago|
|Denver | |
```
The required ou... | Use a derived column to replace city 1. The formula would look something like City1 == "" ? City2 : City 1 | You might try the unpivot transformation. But that may leave you with some blank rows to clean up.
Another possibility would be simulating a coalesce function. [[reference](http://social.msdn.microsoft.com/Forums/sqlserver/en-US/50a9955d-07c4-4ab5-b2eb-ed69f7feaa28/how-to-use-coalesce-function-in-derived-column-compon... | SSIS Expression to Merge Two Columns | [
"",
"sql",
"sql-server",
"ssis",
""
] |
I need to add a new column to a table in my database. The table contains around 140 million rows and I'm not sure how to proceed without locking the database.
The database is in production and that's why this has to be as smooth as it can get.
I have read a lot but never really got the answer if this is a risky opera... | Yes, it is eminently doable.
Adding a column where NULL is acceptable and has no default value does not require a long-running lock to add data to the table.
If you supply a default value, then SQL Server has to go and update each record in order to write that new column value into the row.
**How it works in general... | My example is how do I add a new column to the table by tens of millions of rows and fill it by default value without long running lock
```
USE [MyDB]
GO
ALTER TABLE [dbo].[Customer] ADD [CustomerTypeId] TINYINT NULL
GO
ALTER TABLE [dbo].[Customer] ADD CONSTRAINT [DF_Customer_CustomerTypeId] DEFAULT 1 FOR [CustomerTy... | Add a new column to big database table | [
"",
"sql",
"sql-server",
"database",
""
] |
I'm trying to understand what's the purpose of the join in this query.
```
SELECT
DISTINCT o.order_id
FROM
`order` o,
`order_product` as op
LEFT JOIN `provider_order_product_status_history` as popsh
on op.order_product_id = popsh.order_product_id
LEFT JOIN `provider_order_product_status_history... | It's a technique to retrieve the latest order status.
Because of
```
AND popsh.provider_order_product_status_history_id < popsh2.provider_order_product_status_history_id
```
and
```
AND popsh2.last_updated IS NULL
```
Only those order status that doesn't have any newer status are returned.
For a minimum set examp... | Wait, you have an error:
```
SELECT
DISTINCT o.order_id
FROM
`order` o,
`order_product` as op
LEFT JOIN `provider_order_product_status_history` as popsh
on op.order_product_id = popshs.order_product_id
** YOU HAVE EXCESS 's' HERE ^
LEFT JOIN `provider_order_product_status_history` as pops... | joining same table twice in a mysql query | [
"",
"mysql",
"sql",
""
] |
I'm struggling to figure this one out.
What I want to do is like so:
```
select [fields],
((select <criteria>) return 0 if no rows returned, return 1 if any rows returned) as SubqueryResult
where a=b
```
Is this possible? | In T-sql you can use Exists clause for the given requirement as:
```
select [fields],
case when exists (select <criteria> from <tablename> ) then 1
else 0
end as SubqueryResult
from <tablename>
where a=b
``` | Please try:
```
select [fields],
case when (select COUNT(*) from YourTable with criteria)>0 then
1
else
0
end
as SubqueryResult
where a=b
``` | Return 1 or 0 as a subquery field with EXISTS? | [
"",
"sql",
""
] |
So, I have two tables in SQL Sever 2008 R2:
```
Table A:
patient_id first_name last_name external_id
000001 John Smith 4753-23314.0
000002 Mike Davis 4753-12548.0
Table B:
guarantor_id visit_date first_name last_name
23314 01/01/2013 John ... | Assuming the prefix and suffix are always the same length, just do this:
```
SUBSTRING(external_id, 6, 5)
```
The documentation for `SUBSTRING` is [here](http://technet.microsoft.com/en-us/library/ms187748.aspx) if you want to look at that.
If the prefix and suffix change, also use [CHARINDEX](http://technet.microso... | Try this one
```
SELECT *
FROM TABLE_A inner join TABLE_B on TABLE_A.external_id like '%'+TABLE_B.guarantor_id+'%'
``` | SQL - Join tables with modified data | [
"",
"sql",
"sql-server-2008",
""
] |
I have two tables, say A and B.
Table : A
```
ID_Sender | Date
________________________
1 | 11-13-2013
1 | 11-12-2013
2 | 11-12-2013
2 | 11-11-2013
3 | 11-13-2013
4 | 11-11-2013
```
Table : B
```
ID | Tags
_______________________
1 | Company A
... | ```
SELECT Tags, MAX(Date) AS [Date]
FROM dbo.B INNER JOIN dbo.A
ON B.ID = A.ID_Sender
GROUP BY B.Tags
```
`Demo`
The result
```
Company A November, 13 2013 00:00:00+0000
Company C November, 13 2013 00:00:00+0000
Company D November, 11 2013 00:00:00+0000
``` | try this please let me correct if I wrong. In table B Id = 2 is Company B I am assuming.. if it is right then go ahead with this code.
```
declare @table1 table(ID_Sender int, Dates varchar(20))
insert into @table1 values
( 1 , '11-13-2013'),
(1 , '11-12-2013'),
(2 ,'11-12-2013'),
(... | SQL Query MAX date and some fields from other table | [
"",
"sql",
"date",
"max",
""
] |
I have this simple SQL Update
```
IF(@MyID IS NOT NULL)
BEGIN
BEGIN TRY
UPDATE DATATABLE
SET Param1=@Param1, Data2=@Data2,...
WHERE MyID=@MyID
END TRY
BEGIN CATCH
SELECT ERROR_MESSAGE() AS 'Message'
RETURN -1
END CATCH
SELECT * FROM DATATABLE WHERE MyID= @@IDENTITY
SET @ResultMes... | SQL will catch errors, but an UPDATE statement that does not update any rows, is a valid SQL statement and should not return an error. You can check **@@RowCount** to see how many rows the update statement actually updated
```
IF(@MyID IS NOT NULL)
BEGIN
BEGIN TRY
UPDATE DATATABLE
SET Param... | **IF @@RowCount = 0 BEGIN Select 1/0; END**
I don know if this is a good way of doing it but this is what I just did. The User gets notified with error :) if there are 0 rows affected.
```
Update Table1 Set Table1_Sold = 1 Where table1_ID = '043f258B-8A0B-4CA1-87EC-CDCBD38EE9E1';
IF @@RowCount = 0 BEGIN Select 1/0;... | Error not thrown for SQL update | [
"",
"sql",
"sql-server",
"sql-update",
""
] |
I have a Web Application (Java backend) that processes a large amount of raw data that is uploaded from a hardware platform containing a number of sensors.
Currently the raw data is uploaded and the data is decompressed and stored as a 'text' field in a Postgresql database to allow the users to log in and generate var... | If you are looking to store such strings, you probably want to use [**S3**](http://aws.amazon.com/s3/) (1 object containing
the array string), in this case you will have "backup" out of the box by enabling bucket
versioning. | I have just come across Google Cloud Datastore, which allows me to store single item Strings up to 1Mb (un-indexed), seems like a good alternative to Dynamo | Best solution for storing / accessing large Integer arrays for a web application | [
"",
"sql",
"design-patterns",
"database-design",
"nosql",
"amazon-dynamodb",
""
] |
How could I create a view for a table with subset of the table's records, all of the table's columns, plus additional "flag" column whose value is set to 'X' if the table contains certain type of record? For example, consider the following relations table `Relations`, where values for types stand for `H'-human, 'D'-dog... | ```
CREATE VIEW vHumanDogRelations
AS
SELECT
id,
type,
relation,
related,
-- Consider using a bit 0/1 instead
CASE
WHEN EXISTS (
SELECT 1
FROM Relations
WHERE
id = r.id
AND related = r.related -- Owns someone or this r... | You should be able to put the following `select` into the view definition
```
select *, case when exists
(select * from Relations where id = r.id and relation= 'owns') then 'X'
else '' end as isOwner
from Relations r
``` | Set column value if certain record exists in same table | [
"",
"sql",
"sql-server",
""
] |
I have an Oracle Tree hierarchy structure that is basically similar to the following table called MY\_TABLE
```
(LINK_ID,
PARENT_LINK_ID,
STEP_ID )
```
with the following sample data within MY\_TABLE:
```
LINK_ID PARENT_LINK_ID STEP_ID
-----------------------------------------------
A NULL ... | I think something like this:
```
select link, count(*)-1 as "RESULT COUNT"
from (
select connect_by_root(link_id) link
from my_table
connect by nocycle parent_link_id = prior link_id
start with parent_link_id is null)
group by link
order by 1 asc
``` | Please try:
```
WITH parent(LINK_ID1, LINK_ID, asCount) AS
(
SELECT LINK_ID LINK_ID1, LINK_ID, 1 as asCount
from MY_TABLE WHERE PARENT_LINK_ID is null
UNION ALL
SELECT LINK_ID1, t.LINK_ID, asCount+1 as asCount FROM parent
INNER JOIN MY_TABLE t ON t.PARENT_LINK_ID = parent.LINK_ID
)
select
LINK_... | How to obtain total children count for all parents in Oracle tree hierarchy? | [
"",
"sql",
"tree",
"oracle11g",
""
] |
I want to keep track of opening hours of various shops, but I can't figure out what is the best way to store that.
An intuitive solution would be to have starting and ending time for each day. But that means two attributes per day, which doesn't look nice.
Another approach would be to have a starting time and a `day ... | I think it makes total sense to have two Column One for Open DateTime and One for Close Datetime. Since Once a shop is open it will have to be closed someday/sometime.
**My Suggestion**
I would Create a separate table for shop Opening/Closing Times. Since everytime A shop is opened it will have a close time value a... | The lowest granularity you need is probably minutes (actually, probably 15 minute intervals, but call it minutes).
Possibly you also want to consider day of the week.
If you use a table such as:
```
create table day_of_week_opening_hours(
id integer primary key,
day_of_week ... | What data type to use for opening hours in a database | [
"",
"sql",
"oracle",
"time",
"intervals",
""
] |
Here is my query:
```
select year(p.datetimeentered) as Year, month(p.datetimeentered), datename(month, p.datetimeentered) as Month, st.type as SubType, sum(p.totalpaid) as TotalPaid from master m
inner join jm_subpoena s on s.number = m.number
inner join payhistory p on p.number = m.number
inner join jm_subpoenatypes... | You could do the addition/subtraction as part of the summation:
```
SUM(CASE
WHEN p.batchtype IN ('PU','PA') THEN p.totalpaid
WHEN p.batchtype IN ('PUR','PAR') THEN -p.totalpaid
ELSE 0
END) as TotalPaid
``` | Just use a case statement:
```
Case when p.batch in ('PU','PA') then x + y
else when p.batch in ('PUR, PAR') then x-y
end as YourColumnNameHere
```
If my original interpretation was incorrect, then pobrelkey's suggestion is spot on:
```
sum (
when p.batch in ('PU','PA') then totalpaid
else when p.batch in ('PUR,... | Sum and subtraction to a single column | [
"",
"sql",
"t-sql",
""
] |
I have a table of users and a table of groups and a table linking users with groups. The default group is called "All Users". All new users are placed in this group. They are then linked to more specific groups like sales or purchasing, etc but they stay in "All Users" as well.
I would like to query all the users that ... | ```
SELECT userid, count(*) group_count
FROM user_groups
GROUP BY userid
HAVING group_count = 1
```
If a user is only in one group, it must be the All Users group, and this lists just those users. | This is assuming your table called AllUsers has a unique id for each user called id and your Group table has a foreign key userId linking to AllUsers.id.
SELECT \* FROM AllUsers WHERE AllUsers.id != userId;
That should do it if I understood your question. | Find a user that is not a member of a specific group | [
"",
"mysql",
"sql",
"ms-access",
""
] |
I have a Zip file created and I am unable to delete it using the below command.
`xp_cmdshell 'rm "F:\EXIS\Reports\Individual.zip"'`
It gives an error saying File not found, when I can actually see the file.
I tried using `xp_cmdshell 'del "F:\EXIS\Reports\Individual.zip"'`
But, this asks for a confirmation, which I... | The message is more generic in the sense the file is not found with the current credentials of SQL Server process while accessing the indicated location.
I suspect it is a problem of rights, so please assure the SQL Server proecess has rights to delete file in that location. An alternative suggestion is to perform a "... | Try executing `del`in silent mode like:
```
xp_cmdshell 'del /Q "F:\EXIS\Reports\Individual.zip"'
```
And also: if SQL Server is running on a different machine the path must of course be valid for that machine. | Unable to delete zip files from DB server location using xp_cmdshell | [
"",
"sql",
"sql-server",
"sql-server-2005",
"xp-cmdshell",
""
] |
I am responsible for an old time recording system which was written in ASP.net Web Forms using ADO.Net 2.0 for persistence.
Basically the system allows users to add details about a piece of work they are doing, the amount of hours they have been assigned to complete the work as well as the amount of hours they have sp... | based on the information given i had to do an educated guess about certain table relationships. if you post the table structures, indexes etc... we can complete remaining columns in to this query.
As of right now this query calculates "Days Assigned", "Days Spent" and "Days Remaining"
for the KEY "timesheet\_id and pr... | The Problem what i see in your query is :
1> Alias name is not provided for the Tables.
2> Subqueries are used (which are execution cost consuming) instead of WITH clause.
if i would write your query it will look like this :
```
select distinct t1.timesheet_id,
t1.proposal_job_ref,
... | Slow SQL Server Query due to calculations? | [
"",
"asp.net",
"sql",
"sql-server",
"timeout",
""
] |
I am trying to formulate a query which, given two tables: (1) Salespersons, (2) Sales; displays the id, name, and sum of sales brought in by the salesperson. The issue is that I can get the id and sum of brought in money but I don't know how to add their names. Furthermore, my attempts omit the salespersons which did n... | Try the following
```
select sp.id, sp.name, sum(s.paid_amt)
from salespersons sp
left join sales s
on sp.id = s.spsn_id
group by sp.id, sp.name
``` | Try this:
```
SELECT sp.id,sp.name,SUM(NVL(s.paid_amt,0))
FROM salespersons sp
LEFT JOIN sales s ON sp.id = s.spsn_id
GROUP BY sp.id, sp.name
```
The LEFT JOIN will return the salespersons even when they have no sales.
THE [NVL](http://pic.dhe.ibm.com/infocenter/db2luw/v10r5/index.jsp?topic=/com.ibm.db2.luw.sql.ref.... | trouble formulating an sql query | [
"",
"sql",
"db2",
""
] |
Is there a way to get to the root of the hierarchy with a single SQL statement?
The significant columns of the table would be: EMP\_ID, MANAGER\_ID.
MANAGER\_ID is self joined to EMP\_ID, as manager is also an employee. Given an EMP\_ID is there a way to get to the employee (manager) (walking up the chain) where EMP\... | You want a [Common Table Expression](http://msdn.microsoft.com/en-us/library/ms175972%28v=sql.105%29.aspx). Among other things, they can do recursive queries just like what you're looking for. | It's hard to find a single SQL query that will bring the result with the current structure you have for your table. Like Brett said, you can try with a stored function.
But what I think is best worth looking at is [nested sets](http://en.wikipedia.org/wiki/Nested_set_model), which is one well-confirmed design for tree... | Manager-Managed classic self-join table | [
"",
"sql",
"sql-server-2008-r2",
"self-join",
""
] |
I've created a simple mysql table like [this](https://lh5.googleusercontent.com/-6lsK0AZGV54/UoG5UyVXtSI/AAAAAAAAAXE/ZTpiIjZPYJA/w556-h125-no/table.jpg)
models column takes VARCHAR(30)
But when I execute this query
```
SELECT *
FROM `Vehicle_Duty_Chart`
WHERE models = "SE3P"
LIMIT 0 , 30
```
It returns this
``... | try this:
```
SELECT *
FROM `Vehicle_Duty_Chart`
WHERE TRIM(models) = "SE3P"
LIMIT 0 , 30
``` | Try with below query
```
SELECT * FROM Vehicle_Duty_Chart WHERE models LIKE '%SE3P%' LIMIT 0 , 30
``` | Take string value in where clause - MySQL | [
"",
"mysql",
"sql",
"database",
""
] |
I'm trying to design a new database structure and was wondering of any advantages/disadvantages of using one-to-many vs many-to-many relationships between tables for the following example.
Let's say we need to store information about clients, products, and their addresses (each client and product may have numerous dif... | I think that you have pretty much covered the answer yourself.
To me it really depends on what you are modelling and how you think it will change in the future.
Personally I'd not recommend over engineering solutions, so the one-to-many solution sound great.
However if you expect that your needs will change in say 1 mo... | There seems to be redundancy in both of the designs, using junction tables with an "address type" field with a unique constraint accross all three columns would minimize this.
* client : `id | name`
* client\_address : `client_id | address_id | address_type`
* address : `id | line_one | line_two | line_three | line_fo... | Database design advantages for using one-to-many vs many-to-many relationships | [
"",
"sql",
"database",
"foreign-keys",
"schema",
""
] |
In my server I'm adding values to database using a command like
```
INSERT INTO votes VALUES ('1',0),('2',0),('3',0)
```
The primary key is the first argument of each value key. Sometimes, when adding, the primary key may already exist in the table.
The issue is that, if that happens, I get an error, and it stops th... | `INSERT IGNORE INTO votes VALUES ('1',0),('2',0),('3',0);` | No need to explicitly assign primary key if the primary key is `AUTO_INCREMENT`.
Assuming your table `votes` has 2 columns: `id` and `data`:
The query is:
```
INSERT INTO votes (`data`) VALUES (0),(0),(0)
``` | How to add all list of values to mysql database and keep adding even if there are duplicate primary keys? | [
"",
"mysql",
"sql",
"database",
"sql-insert",
""
] |
Good morning Stack, I am in need of some major help.
I have to convert an EXCEL Formula to a SQL case.
The whole thing keeps falling apart on me when I get to the last section. I can't for the life of me figure out how to set this up properly, and I am tired of getting kicked in the nads over it.
My main problem is h... | a quick paren match shows there may be an error in the last section...
you have this:
```
WHEN TotInChar.TotInChar -(CAST(tmpdc1.[3]AS Decimal (10,2)) + CAST(tmpdc1.[5]AS Decimal (10,2)))- T4MathBlock.TTIV
> 0 THEN
(CASE(CAST(tmpdc.[14]AS decimal(10,2)) > CAST(tmpdc.[3]AS Decimal (10,2)) + CAST... | Simplify it.
Formulate the CASE assuming that all are integers. The details of casting should come later.
At present the solution you have is so cluttered that its impossible to verify if it matches the Excel formula or not. | Converting Excel formula to SQL Case | [
"",
"sql",
"sql-server",
"excel",
""
] |
I get this error when I try to add the foreign key :
> "ORA-00904: "BR\_ID": invalid identifier"
```
create table Branch9
(br_id number NOT NULL,br_name varchar2(25) NOT NULL ,br_address varchar2(30),PRIMARY KEY(br_id))
create table Employee9
(emp_id number NOT NULL,emp_name varchar2(25) NOT NULL UNIQUE,emp_address ... | `br_id` has to be in `Employee9` table:
This is how you add it:
```
ALTER TABLE Employee9 ADD br_id number NOT NULL;
```
Then you can do:
```
ALTER TABLE Employee9
ADD CONSTRAINT fk_br_id FOREIGN KEY (br_id) REFERENCES Branch9 (br_id);
``` | br\_id needs to be a column in Employee9. | SQL - foreign key error | [
"",
"sql",
"oracle",
"foreign-keys",
""
] |
I have a composite primary key on 2 columns in the table I am INSERTing into. I come from working with SQL Server, and I know that if I attempted to insert a duplicate key value into a PK table, it would throw an error.
My problem is, my code is not throwing this kind of error. Can you look at it and see if it's a pro... | If you want to allow the INSERT to proceed and determine whether any duplicates were rejected then you could do something like this
```
Dim cdb As DAO.Database, qdf As DAO.QueryDef, rst As DAO.Recordset
Dim sqlSelect As String, sourceRecords As Long
Set cdb = CurrentDb
sqlSelect = _
"SELECT ColA + ColB, ColC, ... | From the Microsoft DAO Doc ([here](http://msdn.microsoft.com/en-us/library/office/ff197654.aspx)):
> In a Microsoft Access workspace, if you provide a syntactically
> correct SQL statement and have the appropriate permissions, the
> Execute method won't fail — even if not a single row can be modified
> or deleted. The... | detecting whether some records are excluded from an INSERT INTO operation | [
"",
"sql",
"ms-access",
"error-handling",
"vba",
""
] |
First, I'm not sure if the title represent the best of the issue. Any better suggestion is welcomed. My problem is I have the following table:
```
+----+----------+-------+-----------------+
| ID | SUPPLIER | BUYER | VALIDATION_CODE |
+----+----------+-------+-----------------+
| 1 | A | Z | 93788652... | You can update the WHERE clause to filter on the desired pairs:
```
select *
from sample
where (upper(supplier),upper(buyer))
in (('A','X'),('A','Y'),('A','Z'),('B','X'),('B','Y'),('B','Z'));
```
I used the UPPER function based on your mixed case examples. | try this query:
```
select ID,SUPPLIER,BUYER,VALIDATION_CODE from
(select
t2.*,t1.counter
from
validation t2,
(select supplier,count(supplier) as counter from hatest group by supplier)t1
where
t1.supplier = t2.supplier)t3
where t3.supplier in('A','B') and
id = case when t3.counter > 1 then
(select max(id) from valid... | Choose rows based on two connected column values in one statement - ORACLE | [
"",
"sql",
"oracle",
""
] |
I have the following table:
```
RowId, UserId, Date
1, 1, 1/1/01
2, 1, 2/1/01
3, 2, 5/1/01
4, 1, 3/1/01
5, 2, 9/1/01
```
I want to get the latest records based on date and per `UserId` but as a part of the following query (due to a reason I cannot change this query as this is auto generated by a tool but I can write ... | You could use a `NOT EXISTS` condition:
```
SELECT RowId, UserId, Date
FROM MyTable
WHERE 1 = 1
AND NOT EXISTS (
SELECT *
FROM MyTable AS t
WHERE t.UserId = MyTable.UserId
AND t.Date > MyTable.Date
)
;
```
Note that if a user has more than one row with the same latest `Date` value, the query will return all... | Try:
```
SELECT RowId, UserId, Date
FROM MyTable
WHERE 1 = 1
AND EXISTS
(SELECT 1
FROM (SELECT UserId, MAX(Date) MaxDate
FROM MyTable
GROUP BY UserId) m
WHERE m.UserId = MyTable.UserId and m.MaxDate = MyTable.Date)
```
SQLFiddle [here](http://sqlfiddle.com/#!3/9c3a4/1). | Get latest sql rows based on latest date and per user | [
"",
"sql",
""
] |
Database indices are meant for making lookup faster , But how about the performance of a query which uses a regular expression in where clause on a column which is indexed.
Say we have a table `FILES` which has a field `FILE_NAME` and we have a index created on FILE\_NAME.
Then we have a query for searching files wit... | Yes, it *may* improve the performance - but not the way you think.
In normal usage an index allows the DBMS to find rows in a table without scanning through each entry - it can skip over some (for range comparisons, specific values and partial matches such as `LIKE 'ABC%'` but *not* for a query with `LIKE '%XYZ'`). Wh... | Nope. A where clause with a regexp won't use an index for the column. However, a index will work for a `LIKE 'foo%'`, so you may use that for narrowing the results. | impact of database Index on regular expression queries in MySQL | [
"",
"mysql",
"sql",
"regex",
"database",
"indexing",
""
] |
I have a table with two temporal columns. First (name is DATE) is storing the date (not including the time part) and therefor the datatype is DATE. Second column (name is TIME) is for storing the time in seconds and therefor the datatype is NUMBER.
I need to compare this two dates with a timestamp from another table. ... | `date + (time/3600)` [is already a `DATE`](http://docs.oracle.com/cd/E11882_01/server.112/e41084/sql_elements001.htm#sthref172), so you don't need to do `to_date()`. It does have the time part you added though, you just aren't displaying it. If you want to output that as a string in the format you've shown, use `to_cha... | You can use the `INTERVAL DAY TO SECOND` type:
```
SELECT your_date + NUMTODSINTERVAL(your_time_in_seconds, 'SECOND') FROM dual;
```
Example:
```
SELECT TRUNC(SYSDATE) + NUMTODSINTERVAL(39687, 'SECOND') FROM dual;
```
The calculated date with time is: `10-11-2013 11:01:27`
This is a better idea than dividing your ... | Compare date + time with timestamp | [
"",
"sql",
"oracle",
""
] |
I have a two column in my database like:
```
Fisrt Name | Last Name | Full Name
------------------------------------------------
Fayyaz | Jaan |
Danny | Rock |
Tom | Jerry |
```
I have another column "Full Name" that is empty and I want to merge... | Perhaps this will work:
```
UPDATE <table> SET FullName = FirstName || ' ' || LastName
```
Or, seeing your edit, this will probably work:
```
UPDATE <table> SET FullName = CONCAT(FirstName,' ',LastName);
```
And, if that doesn't work, then this will:
```
UPDATE <table> SET FullName = CONCAT(CONCAT(FirstName,' '),L... | try
```
update <table> set FullName = FirstName + ' ' + LastName
```
Otherwise, add the 3rd result to select, something like
```
select firstname, lastname, firstname + ' ' + lastname as FullName from <table>
``` | How to two Column in another column using SQL Query? | [
"",
"mysql",
"sql",
""
] |
I want to implement this type of logic, using DB2:
```
Create Procedure sp_MyProcedure (
IN Var1 Decimal(6, 0),
IN Var2 Decimal(6, 0)
) Language SQL
Dynamic Result Sets 1
Begin
If Exists(Select * from MyTable where CustomerNbr = Var1) Then
return (Select * from MyTable where CustomerNbr = Var1)
Else I... | Here is an ugly select statement that will work:
```
With allrecords as
(
Select 1 as qnum,*
from MyTable
where CustomerNbr = Var1
union all
Select 2 as qnum, *
from MyTable
where CustomerNbr = Var2
union all
Select 3 as qnum, *
from MyTable
where CustomerNbr = 0
)
select *
from allrecords
w... | Best I can think of is as such:
```
SELECT * FROM MyTable
WHERE custNo = Var1
OR (custNo != Var1
AND custNo = Var2)
OR (custNo != Var1
AND custNo != Var2
AND custNo = 0);
``` | what is the best way to select the first query that returns a result in DB2 | [
"",
"sql",
"db2",
"exists",
"with-statement",
""
] |
I have a table user\_address and it has some fields like
```
attributes: {
user_id: 'integer',
address: 'string' //etc.
}
```
currently I'm doing this to insert a new record, but if one exists for this user, update it:
```
UserAddress
.query(
'INSERT INTO user_address (user_id, address) VALUES (?, ?) ' +
... | Make a custom model method that does what you want using Waterline queries isntead of raw SQL. You will be doing two queries, but with Waterline syntax.
Example below (if you don't know about deferred objects then just use callback syntax, but the logic is the same):
```
var Q = require('q');
module.exports = {
at... | The answer above is less than ideal. It also has the method as part of the attributes for the model, which is not correct behavior.
Here is what the ideal native solution looks like that returns a promise just like any other waterline model function would:
```
module.exports = {
attributes: {
user_id: 'integer'... | Waterline ORM equivalent of insert on duplicate key update | [
"",
"sql",
"node.js",
"orm",
"sails.js",
"waterline",
""
] |
This query suggests friendship based on how many words users have in common. in\_common sets this threshold.
I was wondering if it was possible to make this query completely % based.
What I want to do is have user suggested to current user, if **30%** of their words match.
curent\_user total words 100
in\_common th... | May I suggest a different way to look at your problem?
You might look into a similarity metric, such as [Cosine Similarity](http://en.wikipedia.org/wiki/Cosine_similarity) which will give you a much better measure of similarity between your users based on words. To understand it for your case, consider the following e... | OK, so the issue is "users in common" defined as asymmetric relation. To fix it, let's assume that in\_common percentage threshold is checked against user with the least words.
Try this query ([fiddle](http://www.sqlfiddle.com/#!2/1556b/25)), it gives you full list of users with at least 1 word in common, marking frie... | Make HAVING count(*) percentage based - complicated query with percentage calculations | [
"",
"mysql",
"sql",
""
] |
i have two tables of results, a mid-term result table and annual result table.
**Mid-term result table:**

**Annual result table:**

i want to join them and find the total marks of each student for each subje... | I don't think id field make much sense in the result so I omitted it.
```
SELECT Student_id,
Subject_id,
Result_id,
year,
SUM(mark)
FROM result_view
GROUP BY Student_id,
Subject_id,
Result_id,
year
``` | You need GROUP BY:
```
select id, student_id, subject_id,result_id,year,sum(mark) as TotalMark
from result_view
GROUP BY id, student_id, subject_id, result_id, year
```
See my [SqlFiddle](http://sqlfiddle.com/#!2/d89cf/1) | joining two tables and finding the sum of marks for each student | [
"",
"mysql",
"sql",
"database-design",
""
] |
I have a problem with a SQL query. The problem is with the `IN ....`, but I don't know how to correct it. This is the query:
```
SELECT *
FROM Reports, Games, Developers
WHERE Game = SpelID
AND Developer = IDDvl
AND Land IN[‘Japan’,‘USA’,‘UK’,‘Indië’,‘Duitsland’,‘Zweden’]
```
This is the error message:
```
An un... | ```
dagoederen = New OleDb.OleDbDataAdapter("SELECT * FROM Reports , Games,
Developers WHERE Game = SpelID AND Developer = IDDvl AND Land IN (‘Japan’,
‘USA’, ‘UK’, ‘Indië’, ‘Duitsland’, ‘Zweden’)", connectie)
```
You need to replace `[ ]` with `()` after `IN` | The answer is specified in the error provided" In operator without () in query expression". Replace the "[]" with "()" for the IN T-SQL | Visual Studio SQL query not working | [
"",
"sql",
"visual-studio",
""
] |
I am building a leaderboard for some of my online games. Here is what I need to do with the data:
* Get rank of a player for a given game across multiple time frame (today, last week, all time, etc.)
* Get paginated ranking (e.g. top score for last 24 hrs., get players between rank 25 and 50, get rank or a single user... | [Updated]
**Primary key is not good**
You have a unique entity that is [GameID] + [PlayerName]. And composite clustered Index > 120 bytes with nvarchar. Look for the answer by @marc\_s in the related topic [SQL Server - Clustered index design for dictionary](https://stackoverflow.com/questions/3849068/sql-server-clus... | You could look into [indexed views](http://msdn.microsoft.com/en-us/library/dd171921%28SQL.100%29.aspx) to create scoreboards for common time ranges (today, this week/month/year, all-time). | Leaderboard design using SQL Server | [
"",
"sql",
"sql-server",
"database",
"database-design",
"azure-sql-database",
""
] |
I have exported my database to a CSV file and the timestamp now liiks like this:
`1384204028`
How can I convert it to the typical format, for example `2013-01-19 03:14:07` ? | Use [`FROM_UNIXTIME()`](http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_from-unixtime)
```
SELECT FROM_UNIXTIME(1384204028);
```
or (equivalent but with parameter to control the format):
```
SELECT FROM_UNIXTIME(1384204028, '%Y-%m-%d %H:%i:%s');
``` | ```
SELECT DATE_FORMAT(NOW(), '%Y-%m-%d %H:%i:%s')
``` | MySQL Timestamp format | [
"",
"mysql",
"sql",
"date",
"timestamp",
"date-format",
""
] |
I have been practicing SQL query on [W3schools](http://goo.gl/pL6rcn). I'm practicing LIKE in WHERE clause. The following query is working on the site but not working on the SQL SERVER 2008 R2 which is installed on my machine.
```
SELECT * FROM Customers
WHERE CustomerName LIKE '[!uvwxyz]%';
```
This will result in... | Try this:-
In `SQL-SERVER`, to list all customer whose names don't start with `[uvwxyz]`
```
SELECT * FROM Customers
WHERE CustomerName NOT LIKE '[u-z]%';
``` | Please try this query instead.
This will list out all the records with `CustomerName` not starting with `UVWXYZ`:
```
SELECT *
FROM Customers
WHERE CustomerName NOT LIKE 'uvwxyz%';
``` | SQL query showing 2 different results | [
"",
"sql",
"sql-server-2008",
""
] |
In an SQL statement, I am trying to divide two integers (integer 1 is "abc" in my code below, integer 2 is "xyz" in my code), and get a result as a decimal (def in my code below). The decimal result should have a leading 1 or 0 only, followed by a decimal and 3 numbers after the decimal. However my code keeps returning... | Convert to decimal before the divide, not after. The convert for answer format.
```
SELECT
CONVERT( DECIMAL(4,3)
, ( CONVERT(DECIMAL(10,3), abc) / CONVERT(DECIMAL(10,3), xyz) )
) AS def
``` | This should do it. Also add divide by zero check.
```
SELECT CONVERT(DECIMAL(4,3), abc) / NULLIF(xyz,0)
``` | SQL divide two integers and get a decimal value error | [
"",
"sql",
"sql-server",
"asp-classic",
""
] |
I have a database in Microsoft SQL Server and I am using Microsoft SQL Server Management Studio.
I have an option to insert the query result to the file, although the results of the query are not separated by any special signs.
It looks like this
```
select * from table_name
```
Output:
```
18 182 3386 NULL
18 790... | In SSMS:
`Tools` > `Options` > `Query Results` > `Results To Text`
Top option there is `Output Format`, can set a delimiter there. | 
Click here on your SSMS before you execute your query. | Microsoft SQL Server Management Studio - query result as text | [
"",
"sql",
"sql-server",
""
] |
I am coding a dashboard, and I need to pull some data out of Microsoft SQL Server.
For a simple example, I have three tables, one master Category table, and two tables containing values linked to the Category table via a primary/foreign key relationship (Blue and Green value tables).
Using Microsoft SQL Sever (t-sql)... | What you're getting is a Cartesian product. You can see the effects of this by removing the grouping and looking through the data.
For example; if your green table contained 2 rows and your blue table contained 4, your join would return a total of 8 records.
To resolve the problem, well, you're nearly there. You've g... | Something like this would be best done with an APPLY in my opinion. Fast performance-wise, simple to use, and easy to control in case of variations in the query.
IE:
```
SELECT C.[CategoryName], G.[GreenTotal], B.[BlueTotal]
FROM [Category] C
OUTER APPLY (SELECT SUM([GreenValue]) AS [GreenTotal] FROM [Green] WHERE [C... | Using SQL, what is the correct way to total columns from multiple tables into common groups? | [
"",
"sql",
"sql-server",
"group-by",
"sum",
"multiple-tables",
""
] |
I have column `store_name` (`varchar`). In that column I have entries like `prime sport`, `best buy`... with a space. But when user typed concatenated string like `primesport` without space I need to show result `prime sport`. how can I achieve this? Please help me | ```
SELECT *
FROM TABLE
WHERE replace(store_name, ' ', '') LIKE '%'+@SEARCH+'%' OR STORE_NAME LIKE '%'+@SEARCH +'%'
``` | Have you tried using `replace()`
You can replace the white space in the query then use `like`
`SELECT * FROM table WHERE replace(store_name, ' ', '') LIKE '%primesport%'`
It will work for entries like 'prime soft' querying with 'primesoft'
Or you can use regex. | SQL fetch results by concatenating words in column | [
"",
"sql",
"string-search",
""
] |
I have the following table in SQL with lines of an order as follows:
```
RowId OrderId Type Text
----------------------------------------
1 1 5 "Sometext"
2 1 5 "Sometext"
3 2 4 "Sometext"
4 3 5 "Sometext"
... | Try a simple approach:
```
DELETE FROM t
WHERE rowid NOT IN (
SELECT min(rowid) FROM t
GROUP BY orderid, type
)
```
Fiddle [here](http://sqlfiddle.com/#!6/1c2c5/1).
Note that it seems you want to keep the lowers `rowid` when it is repeated. That's why I'm keeping the `min`. | ```
;with cte as
(
Select Row_Number() Over(Partition BY ORDERID,TYPE ORDER BY RowId) as Rows,
RowId , OrderId , Type , Text from TableName
)
Select RowId , OrderId , Type , Text from cte where Rows>1
```
[**Sql Fiddle Demo**](http://www.sqlfiddle.com/#!3/e49d1/7) | How can I remove duplicates in SQL but keep one copy? | [
"",
"sql",
"sql-server",
""
] |
I have a column which has data in this way,
**Table1**
**FullName**
```
Lastname1, Firstname1
Lastname2, Firstname2
Lastname3, Firstname3
```
I want the result to be,
```
Firstname1 Lastname1
Firstname2 Lastname2
Firstname3 Lastname3
```
When I use this query
```
SELECT (substring(Name,charindex(',',Name)+1 ... | Working example: <http://sqlfiddle.com/#!3/0fc0f/16/0>
```
Select
right(name,len(name)-charindex(', ',name)) + ' ' +
left(name,charindex(', ',name)-1)
from @table1;
``` | Provided name doesn't contain a . You can use
```
parsename ( replace ( name, ',','.'),1) + ' ' + parsename ( replace ( name, ',','.'),2)
``` | SQL Divide a string when a comma appears and join it back in reverse order | [
"",
"sql",
"sql-server",
""
] |
I have two tables:
**x\_community\_invites** :
```
id community_id from to registered message seen accepted updated
```
and
**x\_communities** :
```
id name tags registered updated
```
With the query:
```
$query = sprintf("SELECT x_commmunities.* FROM x_commmunities, x_community_invites WH... | You haven't linked tables. You should use JOIN:
```
SELECT x_commmunities.*
FROM x_commmunities
JOIN x_community_invites on x_commmunities.id=x_community_invites.community_id
WHERE x_community_invites.to = '%s' AND x_community_invites.accepted = '%d'
``` | It is an implicit inner join, but the condition that connects the two tables is missing.
```
SELECT x_commmunities.id, x_commmunities.name, COUNT(x_community_invites.*) AS invites
FROM x_commmunities, x_community_invites
WHERE x_commmunities.id = x_community_invites.community_id
AND x_community_invites.to = 'so... | Why isn't this mysql query working? | [
"",
"mysql",
"sql",
"left-join",
""
] |
I want to add a descriptive column at the end of my query results. For example
I have
```
SELECT sum(amount) as Balance FROM tbDebits WHERE CustomerID =@CustomerID;
```
Now if the Balance is positive I want to add another column called 'Description'
in my query results describing each result as positive or negative.
... | I like to use OUTER APPLY when I need to manipulate the results of a SELECT.
I hope it is useful.
```
SELECT t.CustomerID,
c.name,
c.Surname,
Balance.Custom,
case
when sum(Balance.Custom)>0 then 'positive'
when sum(Balance.Custom)<0 then 'negative'
else 'zero'
... | ```
SELECT
sum(amount) as balance,
case
when sum(amount)>0 then 'positive'
when sum(amount)<0 then 'negative'
else 'zero'
end as description
FROM tbDebits
WHERE CustomerID=@CustomerID;
``` | Adding a descriptive/commenting column on query results | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have 2 tables A and b namely.
**Table A has**
```
+------+---------------+
|MANUID|LMD |
+------+---------------+
|1,001 |10/18/2013 7:13|
+------+---------------+
|1,001 |10/18/2013 7:13|
+------+---------------+
|1,001 |10/18/2013 7:13|
+------+---------------+
|1,001 |10/18/2013 7:13|
+------+--------... | ```
SELECT * FROM Table_B
WHERE MANUID IN
(SELECT MANUID FROM Table_A)
```
OR
```
SELECT * FROM Table_B
JOIN Table_A ON Table_B.MANUID = Table_A.MANUID
```
Or if you want to delete records:
```
DELETE * FROM Table_B
WHERE MANUID NOT IN
(SELECT MANUID FROM Table_A)
``` | If you are using SQL query Try this:
```
select tb.*
from Table B as tb, Table A as ta
where tb.MANUID = ta.MANUID
``` | How to compare and remove not used id's in excel | [
"",
"mysql",
"sql",
"excel",
""
] |
I am having some trouble with my Stored Procedure in Oracle 12.1
The blow code is getting an error and I think it has to do with using two EXCEPTION statements in a row?
I am created a stored Procedure for a fake small online DVD company that updates the queue position in the rental queue table. I use an IF statement... | ```
CREATE OR REPLACE PROCEDURE sp_queueorder (
dvdid_sp number,
memberid_sp number,
queueposition_sp number)
IS
dvd_check number;
old_queueposition number;
BEGIN
-- 1st select
BEGIN
SELECT dvdid INTO dvd_check FROM rentalqueue
WHERE DVDid = dvdid_sp and memberid = memberid... | There is a missing END; in your code. Depending on how control is supposed to flow it might be supposed to look like this:
```
CREATE OR REPLACE PROCEDURE sp_queueorder (
dvdid_sp number,
memberid_sp number,
queueposition_sp number)
IS
dvd_check number;
old_queueposition number;
BEGIN
SELECT dvdid INTO dvd_check FROM... | Stored Procedure two exception select statements | [
"",
"sql",
"oracle",
"stored-procedures",
""
] |
I have a table with few columns, one of these columns called \_bandwidth and the value inside it is decimal.
So i wanna type a sql query that adds values to existing value.
Say the value of \_bandwidth of user id 1 is 150.000 and i wanna add 200 to this value so sum would be 350.000
This is the query i typed but it ... | ```
UPDATE Users
SET _bandwidth = _bandwidth + 200
WHERE _ID =1
```
would work | ```
update users
set _bandwidth = _bandiwdth + 200
where _ID = 1
``` | sql server query to add value to existing value | [
"",
"sql",
"sql-server",
""
] |
I am new to T-SQL so have zero knowledge & am using SQL Server 2012. Currently I have a table called `dbo.Securities` which contains two columns. One column is called `PairName` (`nchar(15)`) & the other column is called `RunPair` (`bit`). This table contains 30 rows.
What I would like to do is create 30 new tables th... | You can do this with a cursor to loop through the securities table, and then dynamic sql to create the tables. Looping is a perfectly acceptable way to perform a number of create tables. There's no real way to do that in a set oriented way, which is the usual reason people say to avoid cursors.
```
declare
@sql n... | Note, that you'll want to edit the table schema part in the below code. This loop will build thirty tables. As far as the best and fastest approach? Using `TSQL` this would be faster than manually building each table, but I don't know if it's the fastest method overall.
```
DECLARE @Build TABLE(
ID SMALLINT ID... | T-SQL Create new tables based on another table | [
"",
"sql",
"sql-server",
""
] |
I am trying to update a enroll\_date row to null and it is telling me `"cannot update (%s) to NULL"`, so I tried doing putting `TO_CHAR`and it still doesn't help...
enroll\_date shows this which I want to make it to null
```
ENROLL_DATE
07-FEB-07
```
This is what I have
```
UPDATE ENROLLMENT
SET TO_CHAR(ENROLL_DAT... | The error appears to be telling you that your data model defines `enroll_date` as a `NOT NULL` column. You cannot, therefore, set it to be NULL.
You could modify the table definition to allow NULL values
```
ALTER TABLE enrollment
MODIFY( enroll_date DATE NULL )
```
It seems likely, however, that this was an inten... | Remove the TO\_CHAR function. You're updating a column, not the function'd value
```
UPDATE ENROLLMENT
SET ENROLL_DATE = NULL
WHERE STUDENT_ID ='125'
AND SECTION_ID ='61';
``` | updating date to null | [
"",
"sql",
"oracle",
"null",
"sql-update",
""
] |
I know that writing :
```
SELECT * FROM <ANY TABLE>
```
in a stored procedure will output a result set... what why do we have a return value separately in a stored procedure? where do we use it ?
If any error comes then the result set will be null rite? | First of all you have two distinct ways to return something. You may return a result *set* (i.e. a table) as the result of the operation as well as return *value* indicating either some sort of error or status of the result set.
Also, a return value is limited to a single 32bit integer, whereas a result set can have a... | Because if you use return values you can have a more fine grained control over the execution status and what the error (if any) were and you can return different error codes for malformed or invalid parameters etc and hence add error control/checking on the calling side to.
If you just check for an empty result set yo... | What is the difference between a Result Set and Return value in a SQL procedure? what do they signify? | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
I am using a contained database, after creating the database I attempted to create a user but I got the error:
> You can only create a user with a password in a contained database
My code is:
```
sp_configure 'show advanced options',1
GO
RECONFIGURE WITH OVERRIDE
GO
sp_configure 'contained database authentication', ... | In **SQL Server 2017**, I found that my initial setup did not configure the ["contained databases"](https://learn.microsoft.com/en-us/sql/relational-databases/security/contained-database-users-making-your-database-portable) feature to help this along.
so, at server level you can check the server properties in the UI o... | Create the login and the user separately:
```
CREATE LOGIN MyUser WITH PASSWORD = 'pass@123';
CREATE USER MyUser FOR LOGIN MyUser;
```
The names can be the same but of course they can also be different. | You can only create a user with a password in a contained database | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
I've bloody well done this before, but I plumb forget how.
I have a table of Schools, each with an ID and name.
I have another table of Students, each with a school\_id foreign key.
I want to write a query that'll return a list of schools and the count of their students I have on record; something like this:
```
Sc... | In SQL you can just do:
```
SELECT s.ID, COUNT(*)
FROM schools s
INNER JOIN students ss ON ss.schoolID = s.id
GROUP BY s.ID
```
(about the rails part i can't help you, sorry). | No rails points for me:
```
SELECT
school_name, count(*)
FROM
schools
LEFT JOIN
students
USING(school_id)
GROUP BY
school_id
``` | SELECT name and rowcount? | [
"",
"mysql",
"sql",
"ruby-on-rails",
""
] |
I have never used Bitewise AND in my life. I have researched this operator but it still eludes me as to what it exactly does. So, I will ask with some code I just came across, what is the Bitwise And doing here:
```
CASE
WHEN (ft.Receiver_Status & 2) = 2 THEN '3D'
WHEN (ft.Receiver_Status... | `ft.Receiver_Status & 1`: 1 is 20, so it is pulling out the value of the bit at position 0.
`ft.Receiver_Status & 2`: 2 is 21, so it is pulling out the value of the bit at position 1.
`ft.Receiver_Status & 32`: 32 is 25, so it is pulling out the value of the bit at position 5.
Note that, for example, the `= 32` in `... | The bitwise AND checks to see whether a particular bit is set. It appears `ft.Receiver_Status` is an integer which stores various flags in different bits.
* `1` in binary is `00001` so `ft.Receiver_Status & 1` is checking to see if the first bit is set.
* `2` in binary is `00020` so `ft.Receiver_Status & 1` is checkin... | What is the Bitewise AND doing here | [
"",
"sql",
"bitwise-operators",
"boolean-operations",
""
] |
I have a query and display that gives me employees grouped by departments. It works fine but there is one additional thing that I need that I cannot figure out. By the department name I need to add text that says: "(x employees)", where x is the number of employees in that department. Example:
```
MARKETING (2 employe... | There's not a built in counter you can use. You'll have to loop through each record inside your group by to get a counter for each department.
Also, make sure you scope your query variables
```
<cfoutput query="getEmpsByDept" group="Department">
<cfset empCount = 0>
<cfoutput>
<cfset empCount++>
</cfoutput>... | You need to use a group by in your SQL
If for any given department, if the count is supposed to be different if there is a different name, then you want this
```
<cfquery name="getEmpsByDept" datasource="#application.DSN#" dbtype="ODBC">
SELECT First, Last, Department, COUNT(Department) AS Department Count
F... | How to count the number of employees and add number to title | [
"",
"sql",
"coldfusion",
""
] |
I am trying to write a query (PostgreSQL) to get "Movies with highest number of awards in year 2012."
I have following tables:
```
CREATE TABLE Award(
ID_AWARD bigserial CONSTRAINT Award_pk PRIMARY KEY,
award_name VARCHAR(90),
category VARCHAR(90),
award_year integer,
CONSTRAINT award_unique UNIQU... | ### Get all winning movies
```
SELECT id_movie, awards
FROM (
SELECT aw.id_movie, count(*) AS awards
,rank() OVER (ORDER BY count(aw.id_movie) DESC) AS rnk
FROM award a
JOIN awardwinner aw USING (id_award)
WHERE a.award_year = 2012
GROUP BY aw.id_movie
) sub
WHERE rnk = 1;
```
... | Well you can use [common table expression](http://www.postgresql.org/docs/current/static/queries-with.html) to avoid code duplication:
```
with cte_s as (
select id_movie, count(id_movie) as awards
from Award natural join awardwinner
where award_year = 2012
group by id_movie
)
select
sub.id_movie, sub... | Find movies with highest number of awards in certain year - code duplication | [
"",
"sql",
"postgresql",
"aggregate-functions",
"window-functions",
""
] |
I wrote the following SQL statement to get data from two tables `gendata` & `TrainingMatrix`:
```
SELECT * FROM (SELECT DISTINCT ON ("TrainingMatrix".payroll, "TrainingName", "Institute")"gendata"."Employee Name","gendata"."Position", "gendata"."Department", "TrainingMatrix".*
FROM "TrainingMatrix" JOIN "gendata" ON... | As you have wrapped your actual query into a derived table (the `select .. from (...) as foo`) your "table" isn't called `TrainingMatrix` any longer. You need to reference it using the alias you use for the derived table:
```
select *
from (
... you original query ..
) as foo
where foo."ExpiryDate" - current_date <=... | 100% what [@a\_horse already said](https://stackoverflow.com/a/19976236/939860). Plus a couple more things:
**Format** your query so it's easy to read and understand for humans before you try to debug. Even more so, before you post in a public forum.
Use [**table aliases**](https://www.postgresql.org/docs/current/sql... | Missing FROM-clause entry for a table | [
"",
"sql",
"database",
"postgresql",
"select",
"greatest-n-per-group",
""
] |
i'm trying to join table Group on my link table userGroup, to get the groups where user with id 30 is not a member, but i can't seem to get it right.
joining with no conditions returns this
```
SELECT Groups.ID, Groups.Name, UserGroup.groupID, UserGroup.userID
FROM Groups LEFT OUTER JOIN UserGroup ... | You actually want to join trying to find where usergroup.userID = 30, not <> 30. From that join you want to return the records where there *is no* such usergroup record.
Try something like this:
```
SELECT Groups.ID, Groups.Name, UserGroup.groupID, UserGroup.userID
FROM Groups
LEFT OUTER JOIN Us... | " to get the groups where user with id 30 is not a member"
```
SELECT *
FROM Groups g
WHERE NOT EXISTS (SELECT 1 FROM UserGroup WHERE groupID = g.iD and userID = 30);
```
seems more natural to me in your case. | sql conditional join getting wrong results | [
"",
"sql",
"sql-server-2008",
"join",
""
] |
Not sure why the Query and View Designer is not appearing as per
<http://msdn.microsoft.com/en-us/library/vstudio/ms172013.aspx>
It's an ASP.net project with database in the AppData folder, and a connection using SQL 2008 Express.
If it helps the connection string is:
Data Source=.\SQLEXPRESS;AttachDbFilename="C:\f... | I have been having the same problem and think I have found the solution.
When you are adding the connection to the Database, in the Add Connection Dialog.
Click 'Change...' next to the Data source
Dialog opens showing 'Change Data Source'
You probable have selected 'Microsoft SQL Server' and then below that there is... | Was searching for a solution to a similar issue. Unable to use Query Designer for a local mdf file database. This is what I found...hope it helps someone.
Reading the comments here (<http://social.msdn.microsoft.com/Forums/sqlserver/en-US/ed4675d3-aa84-47db-bdf5-f852355409e6/query-designer-not-displaying-in-visual-stu... | Visual Studio 2013 SQL Query and View Designer not appearing | [
"",
"sql",
"designer",
"visual-studio-2013",
""
] |
I am using Sybase and I am doing a select which returns me a column called "iftype", but its type is int and I need to convert into varchar. When I try to do the select without the convert function I get this error:
> Error code 257, SQL state 37000: Implicit conversion from datatype 'VARCHAR' to 'INT' is not allowed.... | Use the convert function.
```
SELECT CONVERT(varchar(10), field_name) FROM table_name
``` | Use the `STR` function:
```
SELECT STR(field_name) FROM table_name
```
---
## **Arguments**
**float\_expression**
Is an expression of approximate numeric (float) data type with a decimal point.
**length**
Is the total length. This includes decimal point, sign, digits, and spaces. The default is 10.
**decimal**
... | Convert INT to VARCHAR SQL | [
"",
"sql",
"select",
"type-conversion",
"sybase",
""
] |
I have the following problem in my sqlite database there are values stored and for some purposes I need to remove entries.
But before I need to get the id for the rows which I would like to remove. To get the id tried to use the following query:
```
select commonid from TestData where coordinate_x=5.707523 and coordin... | This works for me:
```
sqlite> .schema t
CREATE TABLE t (f double);
sqlite> select * from t;
1.23456789
2.23456789
3.23456789
sqlite> select * from t where f = 1.23456789;
1.23456789
sqlite> select * from t where f like '1.23456789';
1.23456789
sqlite> select * from t where f like '1.234%';
1.23456789
sqlite> select *... | You can, but it would be smarter (and probably faster) to do
```
SELECT commonid FROM TestData WHERE coordinate_x=5.707523 AND
ABS(coordinate_y-6.693945)<0.000005;
```
or
```
SELECT commonid FROM TestData WHERE coordinate_x=5.707523 AND
coordinate_y BETWEEN 6.69394 AND 6.69395;
``` | How can I use like with float numbers in sqlite? | [
"",
"sql",
"sqlite",
"floating-point",
"numbers",
"precision",
""
] |
Here's the scenario:
I'm migrating data from an old system to a new system.
The old system had 2 tables that represented comments and their replies.
The new system has a single table for comments that allows nested comments. So, it has a self-referencing foreign key.
I need to move data from the 2 tables into 1.
H... | So it looks like if I were using SQL 2008 or above, I could use the `MERGE` statement with the `OUTPUT` keyword. Unfortunately, I need to support SQL 2005 which does not have the `MERGE` statement. I ended up using nested loops. | Without a test database in front of me, you can do it using the `OUTPUT` keyword in MSSQL. Should be enough to get you started:
```
DECLARE @NewIDs Table
(
NewID INT,
OldID INT
)
INSERT INTO NewTable
OUTPUT NewTable.ID,
OldTable.ID
INTO @NewIDs
SELECT NULL As ParentCommentID, Othercolumns
FROM OldParen... | SQL Migration Script - nested loops | [
"",
"sql",
"sql-server",
"data-migration",
""
] |
I have the following SQL statement: `SELECT sys_context('userenv','db_name') FROM dual;`. I stored it inside a SQL file called `db.sql` in C:
Now, I can run this file:
> @C:\db.sql
I know we can invoke the file just as @db, but, when I try it, I get this error:
```
SQL> @db
SP2-0310: unable to open file "db.sql"
``... | Found the answer myself :) here sharing this...
Always these files will be looked in Bin of your Oracle Client. Most user create ORACLE\_HOME environmental variable at time of installation and the files will be looked in ORACLE\_HOME\Bin
1. So create a environmental variable if not present already pointing
to [dri... | SQLPATH seems like an environment variable.
RClick on your MyComputer. Go to "Advanced System Settings". Under "Advanced" Tabs click on "Environment Variables..." and there you can set the SQLPATH under your system variables if you have admin rights. | From where the Stored Procedure file will be called when using @filename in SQL plus | [
"",
"sql",
"oracle",
"stored-procedures",
""
] |
It's easy to understand why left outer joins are not commutative, but I'm having some trouble understanding whether they are associative. Several online sources suggest that they are not, but I haven't managed to convince myself that this is the case.
Suppose we have three tables: A, B, and C.
Let A contain two colum... | If you're assuming that you're JOINing on a foreign key, as your question seems to imply, then yes, I think OUTER JOIN is guaranteed to be associative, as covered by [Przemyslaw Kruglej's answer](https://stackoverflow.com/a/20022519/1709587).
However, given that you haven't actually specified the JOIN condition, the p... | In this thread, it is said, that they are not associative: [Is LEFT OUTER JOIN associative?](https://stackoverflow.com/questions/9614922/does-the-join-order-matters-in-sql)
However, I've found some book online where it is stated, that OUTER JOINs are associative, when the tables on the far left side and far right side... | Are left outer joins associative? | [
"",
"sql",
"join",
"outer-join",
""
] |
I'm currently working on an interesting problem and though I'd share it to solicit ideas.
I have a table, lets call it *Table One*. Each *ID* has an **effective date range** implied by **datetimes** (these are actually DATETIME types, even though I've presented them strangely below) *Date A* and *Date B*. So for examp... | you can do it with a join, but considering your data types, it's a bit convoluted. The best to do is to use, in your Table One, columns with the DATE datatype, instead of strings. Then you can do something like that :
```
SELECT t2.DateStr, t1.Id
FROM TableOne t1
JOIN TableTwo t2 ON t2 StartDatetime BETWEEN t1.DateA A... | What you need as a calendar table - like you have but using actual `DATETIME`, then just join you data on to it as
```
SELECT c.ShortDate, t.Id, t.StartDate, t.EndDate
FROM dbo.Calendar c
JOIN tbl t ON c.ShortDate BETWEEN t.StartDate AND t.EndDate
ORDER BY c.ShortDate, t.Id
```
Sidenote: keep all dates as `DATETIME` ... | SQL - Creating a historical fact table from latest snapshot data | [
"",
"sql",
"sql-server",
"sql-server-2008",
"datetime",
"business-intelligence",
""
] |
i need the LAST\_NAME, JOB\_ID, SALARY columns from table workers and the job id needs to be SH\_CLERK or SA\_REP and the SALARY column CANNOT equal to 1000,2600,3000,7000,8000 or 9000
```
SELECT `LAST_NAME`, `JOB_ID`, `SALARY` FROM `workers`
WHERE `JOB_ID` = SH_CLERK OR SA_REP AND `SALARY` != 1000 and 2600 and 3000 a... | Put quotes around strings.
Switch multiple `OR`'s to using `IN` instead.
```
SELECT LAST_NAME, JOB_ID, SALARY
FROM workers
WHERE JOB_ID IN ('SH_CLERK', 'SA_REP')
AND SALARY NOT IN (1000, 2600, 3000, 7000, 8000, 9000);
``` | ```
SELECT LAST_NAME, JOB_ID, SALARY
FROM workers
WHERE JOB_ID IN ('SH_CLERK', 'SA_REP') AND
SALARY NOT IN (1000, 2600, 3000, 7000,8000, 9000)
``` | SQL table where clause error | [
"",
"mysql",
"sql",
""
] |
I have a table with CUSTOMERNAME and REDIRECTNAME columns in my REDIRECTS table as follow
```
ID NAME REDIRECTLINK
1 Gregory XYUS_555
2 Sam VYU_787
3 Smith XYUS_555
4 John PPIU_987
```
So basically I want to update the duplicate and append a number to it like for Smith ... | First determine the subnumber of the RedirectLink by using ROW\_NUMBER() (and subtract 1 to make it start at zero). Then use it in an update to update all records that have a subnumber above zero.
```
with NT as (
select
ID,
Row_Number() over (PARTITION BY RedirectLink ORDER BY ID)-1 as Nr
from Table1
)
update T... | You can `UPDATE` using `JOIN`:
```
;WITH cte AS
(
SELECT *,
ROW_NUMBER() OVER (PARTITION BY NAME ORDER BY Id DESC) AS rn
FROM REDIRECTS
)
UPDATE REDIRECTS
SET REDIRECTLINK = REDIRECTLINK + '01'
FROM cte
INNER JOIN REDIRECTS
ON REDIRECTS.Id = cte.Id
WHERE cte.rn = 1;
```
You can see [this post](... | Updating duplicate column with value | [
"",
"sql",
"sql-server-2008",
""
] |
This is pertaining to Oracle 11g development. Can a column from its view definition be defined to transform its data?
For example,
```
CREATE VIEW TestView AS SELECT Col1, Col2, TestColumn FROM TestTable;
```
For TestColumn, originating Table holds values= (True or False). But should be displayed as (Y,N) . How coul... | ```
CREATE VIEW TestView AS
SELECT Col1,
Col2,
DECODE( TestColumn, 0, 'N', 1, 'Y', null ) AS TestColumn
FROM TestTable;
```
[SQLFIDDLE](http://sqlfiddle.com/#!4/32564/1/0) | You can do that in query itself
```
SELECT CASE WHEN COL='TRUE' THEN 'Y' WHEN COL='FALSE' THEN 'NO' END AS NEW_COL_NAME ...
``` | Oracle View Data Transformation | [
"",
"sql",
"oracle",
"view",
""
] |
I am trying to insert some data to SQL Server 2008 R2 by using JAP and HIBERNATE. Everything "works" except for that it's very slow. To insert 20000 rows, it takes about 45 seconds, while a C# script takes about less than 1 second.
Any veteran in this domain can offer some helps? I would appreciate it a lot.
Update: ... | To enable [JDBC batching](http://docs.jboss.org/hibernate/orm/4.0/devguide/en-US/html/ch04.html) you should initialize the property hibernate.jdbc.batch\_size to between 10 and 50 (int only)
```
hibernate.jdbc.batch_size=50
```
If it's still not as fast as expected, then I'd review the document above paying attention... | ## The problem
One of the major performance hits if you use Hibernate as your ORM is the way its "dirty check" is implemented (because without Byte Code Enhancement, which is standard in all JDO based ORMs and some others, dirty checking will always be an inefficient hack).
When flushing, a dirty check needs to be ca... | JPA with HIBERNATE insert very slow | [
"",
"sql",
"sql-server",
"database",
"hibernate",
"jpa",
""
] |
I'm having trouble getting a sproc to give me this type of output:
```
+-----------+------------------+
| Month | NoOfModifcations |
+-----------+------------------+
| Jan 2008 | 5 |
| Nov 2008 | 6 |
| Feb 2010 | 20 |
| Jul 2013 | 7 |
+-----------+----... | This should do:
```
SELECT CONVERT(VARCHAR(4),YEAR(LastModifedDate)) + ' ' +
CONVERT(VARCHAR(3),DATENAME(MONTH,LastModifedDate)) AS Dates,
COUNT(*) as Number
FROM aims.Modification
WHERE CompanyID = @companyID
AND LastModifedDate >= DATEADD(MONTH,@numberOfMonths * -1,GETDATE())
GROUP BY CONVERT(... | ```
SELECT YEAR(LastModifedDate), MONTH(month) as Dates, count(*) as Number
FROM aims.Modification
WHERE CompanyID = @companyID
AND LastModifedDate >= DATEADD(month, @numberOfMonths * -1, GETDATE())
GROUP BY YEAR(LastModifedDate), MONTH(LastModifiedDate)
ORDER BY YEAR(LastModifedDate), MONTH(LastModifiedDate)
```
... | Count number of rows within each month of a datetime, group by year month | [
"",
"sql",
"sql-server",
"datetime",
"count",
"group-by",
""
] |
Is there a function that is similar to `COALESCE` but for values that are not `NULL`?
I need to replace a return value of a scalar-valued-function with another value if it returns the string literal `N/A`. If it would return `NULL` i could use:
```
SELECT COALESCE(dbo.GetFirstSsnInFromSsnOut(RMA.IMEI), RMA.IMEI) AS [... | Perhaps there you can use [NULLIF](http://technet.microsoft.com/en-us/library/ms177562.aspx) function, for example:
```
SELECT ISNULL(NULLIF(dbo.GetFirstSsnInFromSsnOut(RMA.IMEI), 'N/A'), RMA.IMEI) AS [IMEI to credit]
, OtherColumns
FROM dbo.TableName;
``` | If you can't change `GetFirstSsnInFromSsnOut` to return Null-Values then try this:
`SELECT COALESCE(dbo.GetFirstSsnInFromSsnOut(NULLIF(RMA.IMEI, 'N/A')), RMA.IMEI) AS [IMEI to credit]
, OtherColumns
FROM dbo.TableName` | ISNULL/COALESCE counterpart for values that are not NULL | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2005",
"sql-function",
""
] |
I have an ids range (it defines by startId and stopId). I have a table with some records(every record has an id - primaty key). Now I need to select all ids from specified range that don't exist in the table. I am using postgres database. Please suggest what options I have to perform such query. | You may look at [generate\_series](http://www.postgresql.org/docs/9.3/interactive/functions-srf.html)() function.
Then use an except clause to get the difference.
```
select s.a from generate_series(<start>, <stop>) as s(a)
except
select id from <myTable>
where <yourClause>
--order by a
```
See [SqlFiddle](http://sq... | You can use the: <http://www.postgresql.org/docs/9.1/static/functions-srf.html>
```
SELECT * FROM generate_series(startId,stopId) AS all_ids WHERE id NOT IN (SELECT id FROM table WHERE id
>= startId AND id <= stopId) as existent_ids;
``` | Select ids that don't exist in a table | [
"",
"sql",
"database",
"postgresql",
""
] |
I've 2 columns which I want to use a condition on. But I get this error message and my query is correct I'll come to that soon.
> Msg 8114, Level 16, State 5, Line 1
> Error converting data type varchar to float.
So this is the problem, I have a temp-table in which ID-number looks like this 9001011234 we can call i... | You have a `VARCHAR` format that can't be trivially transformed to a number. I'd use `REPLACE(b,'-','') = a` to fix the format, and let SQL Server take care of the rest. | Say:
```
where A = CAST(REPLACE(B, '-', '') AS float)
``` | SQL converting float to varchar | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I'm using a `CASE` statement to help populate a temp table, but for some reason I'm getting an Operand type clash error:
```
CREATE TABLE #users
(
id INT IDENTITY (1, 1),
userid UNIQUEIDENTIFIER,
username VARCHAR(50),
sysrole VARCHAR(50)
)
--Insert all loadtest users into temp ta... | If just you want to assign five string values to 500 users arbitrarily, one to each hundred, you should consider a different approach:
```
WITH enumerated AS (
SELECT
id,
username,
rn = ROW_NUMBER() OVER (ORDER BY username)
FROM user
WHERE username LIKE '%test%'
)
SELECT
rn,
id,
username,
sys... | I have vague recollections that tinyint only goes up to 127. You can look it up. The solution is to change the datatype to smallint.
**Edit**
I looked it up. I had the right value, but for the wrong database engine. Solution still applies though. | Temp Table giving Operand Clash error | [
"",
"sql",
"sql-server-2008",
"t-sql",
""
] |
I have a database with the following tables:
```
student(sid, name,address)
course(cid,type,department)
takes(sid,cid,score)
```
The query which i need to solve is
Find the students such that, for each course they take, their score on the course is higher than any other student who has taken that same course.
I kn... | ```
SELECT
s.sid,
s.name
FROM student s
WHERE NOT EXISTS (
SELECT *
FROM takes t1
JOIN takes t2 ON (t1.cid = t2.cid AND t1.sid <> t2.sid AND t2.score > t1.score)
WHERE t1.sid = s.sid
);
```
We're selecting all students, for whom we can't find any course they took where someone else had a higher... | Try this:
```
SELECT s.*
FROM student s
INNER JOIN (
SELECT t1.*
FROM takes t1
LEFT JOIN takes t2
ON (t1.cid = t2.cid AND t1.score < t2.score)
WHERE t2.cid IS NULL
) b ON b.sid = s.sid
```
`sqlfiddle demo`
You can see in the fiddle that if two users have the same score that is the best, both will ... | Comparing each value with rest in oracle | [
"",
"sql",
"oracle",
"oracle11g",
""
] |
I have created the following view in MySQL:
```
CREATE VIEW MYVIEW AS (
SELECT A.FNAME
, A.LNAME
, B.EMAIL
FROM EMPLOYEE A, EMPEMAIL B
WHERE A.EID = :empId
AND A.EID = B.EID
AND B.EMAILTYP = :emailType)
```
I have to make `empId` and `emailType` dynamic i.e. get the result for the desired values of `empId... | Just create the view without the parameters (i.e., to take care of the join only):
```
CREATE VIEW MYVIEW AS (
SELECT A.FNAME
, A.LNAME
, B.EMAIL
, A.EID AS EID -- added to be used in the WHERE
, B.EMAILTYP AS EMAILTYP -- added to be used in the WHERE
FROM EMPLOYEE A, EMPEMAIL B
WHERE... | You can use this solution with a function -
```
CREATE FUNCTION func() RETURNS int(11)
RETURN @var;
CREATE VIEW view1 AS
SELECT * FROM table1 WHERE id = func();
```
Using example:
```
SET @var = 1;
SELECT * FROM view1;
``` | How to pass dynamic parameters to a MySQL view | [
"",
"mysql",
"sql",
"select",
"view",
"mysql-workbench",
""
] |
I have a MySQL table that looks like the following:
```
player_rankings | CREATE TABLE `player_rankings` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`award_id` int(11) NOT NULL,
`rank_1` int(11) DEFAULT NULL,
`rank_2` int(11) DEFAULT NULL,
`rank_3` int(11) DEFAULT NULL,
`rank_4` i... | To get the sum of points per rank:
```
SELECT user_id,
sum(rank1Points) rank1Points,
sum(rank2Points) rank2Points,
sum(rank3Points) rank3Points,
sum(rank4Points) rank4Points,
sum(rank5Points) rank5Points
FROM (
SELECT pr.rank_1 user_id, count(*) * 5 rank1Points, 0 rank2Points, 0 rank3Points, 0 rank4Points,... | For your table structure may be good solution is calculate all in script. Just get all rows and then calculate.
If you want make all in one SQL query then you can try use UNION for 5 subqueries
```
SELECT user_id, rank FROM(
SELECT rank_1 AS user_id, 5 AS rank FROM player_rankings
UNION
SELECT rank_2 AS user... | MySQL query to count and score multiple columns | [
"",
"mysql",
"sql",
""
] |
I currently have use of If Not RS.EOF and Not RS.BOF is a DAO Recordset, but I cannot use DAO in the new SQL backend environment. Code is as follows:
```
Function CloseSession()
'This closes the open session
Dim Rs As DAO.Recordset
Set Rs = CurrentDb.OpenRecordset("SELECT * FROM Tbl_LoginSessions WHERE fldLoginKey ="... | This was my answer:
```
Function LogMeIn(sUser As Long)
' was Function LogMeIn()
'/Go to the users table and record that the user has logged in
'/and which computer they have logged in from
Dim con As ADODB.Connection
Dim cmd As ADODB.Command
Dim strSQL As String
'/Dim sUser As Long
Dim strComputerName As String, st... | In the DAO case your code is using (DAO) Recordset objects and avoiding explicit SQL statements; in the ADO case you're using explicit SQL statements and avoiding using (ADO) Recordset objects. As such, the short answer to your question is: use ADO Recordset objects, and you will have your `BOF` and `EOF` properties li... | If Not RS.EOF and Not RS.BOF then written for ADODB versus current DAO format | [
"",
"sql",
"ms-access",
"vba",
""
] |
Having a problem with one of my SQL queries. This is my query:
```
explain
SELECT DISTINCT profiles.hoofdrubriek, profiles.plaats, profiles.bedrijfsnaam, profiles.gemeente, profiles.bedrijfsslogan, profiles.straatnaam, profiles.huisnummer, profiles.postcode, profiles.telefoonnummer, profiles.fax, profiles.email, prof... | Well, if an `or` is causing a problem, then the simplest solution is to break the query into two pieces and put them together using `union` (in your case, because of the `distinct`). Rectifying the `where` clause using an index is going to probably be impossible, because it references two different columns:
```
SELECT... | I think Gordon is right about using UNION, but you can make the UNION much more efficient:
In the first query below, since you are only referring to the `profiles` table, you can remove the joins, they will only serve to cause duplicates that subsequently need to be removed. Then in the second, you can change the JOIN... | SQL query no using indexes properly | [
"",
"mysql",
"sql",
"join",
"indexing",
""
] |
I have a column which contains data but the problem is that this column has data type of varchar(50) and it has to be this due to some reasons,now what i want to do is while selecting data from table , i want to treat this column as date so that i can use it in where clause. i am using the code below for converting it ... | Try this:
```
SET DATEFORMAT dmy;
select case when isdate(sowingDate) = 1 then CONVERT(date,sowingDate,103) end [date] from tblAgriculture_staging
```
or (if you are using sql 2012)
```
SET DATEFORMAT dmy;
select case when TRY_CONVERT(date, sowingDate) IS NOT NULL then CONVERT(date,sowingDate,103) end [date] from tb... | > but it converts some values and then gives an error this is my sample
> data
because some data are in invalid format or contains incorrect symbols.
Try this:
```
select CONVERT(date,ltrim(rtrim(sowingDate)), 103) from tblAgriculture_staging
```
or examine your values:
```
select ISDATE(sowingDate) as IsDate, so... | Convert String to date in select statement | [
"",
"sql",
"sql-server",
"date",
""
] |
I've come from a Postgres/MySQL world, so am wondering if there's a difference between these 2 queries in SQL server:
```
SELECT e.employee_id, s.salary
FROM employees e INNER JOIN salaries s
ON e.employee_id = s.employee_id
SELECT e.employee_id, s.salary
FROM employees e, salaries s
WHERE e.employee_id = s.employee... | The new join syntax was introduced with [SQL-92](http://en.wikipedia.org/wiki/SQL-92) and is supported by SQL Server (at least as far back as SQL Server 2000) and most other DBMSs these days. Performance wise, they are equivalent, but generally I recommend the new SQL-92 syntax for new code. | There is no functional difference between the two. The latter (known as implicit join) is considered outdated, and is usually frowned upon. | Difference in SQL server INNER JOIN syntax? | [
"",
"sql",
"sql-server",
""
] |
This query is working fine:
```
SELECT posts.titulo as value,
posts.id as id,
posts.img_src as img,
posts.id_familia,
posts.tiempo,
posts.votos,
familias.clave,
familias.id as fm... | Try something like this:
```
SELECT posts.titulo AS value,
posts.id AS id,
posts.img_src AS img,
posts.id_familia,
posts.tiempo,
posts.votos,
familias.clave,
familias.id AS fm,
textos.clave,
textos.texto AS familia,
COALESCE(COM_COUNT.NUM_COMMENTS,0) AS num_comments
FROM posts
INNER JOIN familias ... | Try this:
```
SELECT posts.titulo as value,
posts.id as id,
posts.img_src as img,
posts.id_familia,
posts.tiempo,
posts.votos,
familias.clave,
familias.id as fm,
textos.clave,
textos.texto as familia,
count(comentarios.id)
FROM posts INNE... | Adding a count from another table to existing query | [
"",
"mysql",
"sql",
"count",
""
] |
I have a db with 3 tables, as following
```
CREATE TABLE Person
(id_pers number (3),
name varchar(20) NOT NULL,
phone number (15),
PRIMARY KEY(id_pers)
);
CREATE table Book(
id_book number(3),
title varchar(30),
about varchar (200),
nr_of_books number (3),
type varchar (11),
PRIMARY KEY(id_book)
... | This will include your title in the result, and it won't give errors about missing group by. I am not sure this is all you want, though...
```
SELECT au.id_book, bk.title, count(au.id_aut)
FROM author au
JOIN book bk
ON au.id_book = bk.id_book
JOIN person p
ON p.id_pers = au.id_aut
GROUP... | ```
SELECT au.id_book, count(au.id_aut)as count
FROM author au join book bk ON au.id_book = bk.id_book
JOIN person p ON p.id_pers = au.id_aut
GROUP BY au.id_book
HAVING (count=2)
``` | How do i select datas from two different tables when count() = 2 with join? | [
"",
"sql",
"oracle-sqldeveloper",
""
] |
I have a classic ASP page with a simple html table, and I want to loop the table rows based on a unknown number of records pulled from the database, however, when I am looping the records with a do/while loop, I am getting an error saying that Either BOF or EOF is True. I want every other row of the table to alternate ... | I know I am rusty on this one but try this:
```
<%
Dim oddFlag
oddFlag = 1
do while not rsTest.eof
if oddFlag=1 Then
oddFlag=0
Response.write("<tr class='odd'>")
Response.write("<td colspan='5'>")
Response.write(rsTest.Fields.Item("field").Value)
Response.write("</td></tr>")
else
... | Since the other answers don't mention this: the problem with your code is that you're doing MoveNext twice, and the second one doesn't test if the first one already reached the EOF.
In any case, that's a needlessly complicated way to do alternating colors.
```
dim i, rs
'... database stuff, table header, etc.
i = 0
D... | Classic ASP do while loop showing error | [
"",
"sql",
"asp-classic",
"do-while",
""
] |
The cells in an N-dimensional space are modelled with the 2 tables below. A script is needed that takes a single cell (by CellID) and returns all the other cells that are "inline" with the given cell along each axis (including itself).
For example, suppose the space has 3 dimensions (X, Y, Z) and X has 2 positions, Y ... | ```
select x.AxisCode, a2.CellID
from CellAxes a1
inner join CellAxes a2 on a2.AxisCode = a1.AxisCode
inner join CellAxes x on x.CellID = a1.CellID
where (a1.AxisCode = x.AxisCode or a1.PositionOnAxis = a2.PositionOnAxis)
and a1.CellID = @CellID -- Cell to match against
group by x.AxisCode, a2.CellID
having count(*) = ... | Based on your original two tables in your question, you can write dyanamic SQL to create columns that you can then use to compare with whatever you are using to define "inline".
```
-- Build list of column values to pivot
DECLARE @cols NVARCHAR(1000);
SELECT @cols =
STUFF((SELECT N'],[' + axiscode
FROM (SELECT ... | T-SQL puzzler - given a cell in an N-dimensional space, return the cells that are inline with the given cell along each axis | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
From the following data, how can I select all the children a parent has ordered by the perCent desc of those children?
Parents are type 3 only.
I tried the below, but that orders the entire result set. I need to order by each parents childrens perCent. You'll see in the expected results:
```
select b.id, b.type, b.p... | Keep the same general join, but apply an order by across multiple columns:
```
select child.id as childId, child.perCent
from scores parent
join scores child
on parent.id = child.parent
where parent.type = 3
order by parent.id, child.perCent desc
```
This says, first order by the parent (such that all children for... | ```
select id,perCent from scores
where parent in (select id from scores where type=3)
order by parent, percent desc
``` | Select records and order by scores desc | [
"",
"mysql",
"sql",
""
] |
I'm creating a View in MySQL that will group the titles of movies by the number of times they have been rented, in descending order. So far, I have this:
```
CREATE VIEW number_of_rentals as
SELECT title
FROM film
JOIN inventory ON film.film_id=inventory.film_id
JOIN rental ON inventory.inventory_id=rental.inventory_i... | ```
SELECT f.title
FROM film f
JOIN inventory i ON f.film_id = i.film_id
JOIN rental r ON i.inventory_id = r.inventory_id
group by f.title
order by count(*) desc
``` | Your SELECT in your view should probably look very similar to this:
```
SELECT title, count(title) as rentals
FROM film
JOIN inventory ON film.film_id=inventory.film_id
JOIN rental ON inventory.inventory_id=rental.inventory_id
GROUP BY title
ORDER BY count(title) DESC;
```
Here's a basic [sqlfiddle example](http://... | In MySQL, how do I order by the number of times a specific instance appears? | [
"",
"mysql",
"sql",
"sql-order-by",
""
] |
i have 3 tables:
members(nic,name)
awards(nic,aw\_name)
championships(nic,ch\_name)
a person can have multiple awards or championships. for example Richard has 2 awards and 3 championships, and Steve does not have any award or championship.
now i'd like to list of persons with awards and championships. for example... | Try this:
```
SELECT
members.nic,
members.name,
awards.aw_name,
championships.ch_name
FROM
(
SELECT
CASE WHEN @curNic = members.nic THEN @curRow := @curRow + 1 ELSE @curRow := 1 END num,
@curNic := members.nic nic,
name
FROM
members LE... | Try this out.
```
SELECT m.nic,
m.name,
a.aw_name,
c.ch_name
FROM members m
LEFT JOIN awards AS a ON m.nic = a.nic
LEFT JOIN championships AS c ON m.nic = c.nic
GROUP BY m.nic, m.name
``` | how to left join 3 tables in mysql | [
"",
"mysql",
"sql",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.