Etienne
Etienne

Reputation: 7201

Create computed column with string in formula

I want to create a computed column in SQL SERVER and set the formula to this

([Category] +  '.aspx?ID=' + [Post_ID])

Not working though......what am i missing?

Category and Post_ID are current columns in the table

Upvotes: 3

Views: 2193

Answers (3)

Etienne
Etienne

Reputation: 7201

This actually sorted it out for me at the end.....

NavigateUrl='<%# String.Format("{0}.aspx?ID={1}", DataBinder.Eval(Container.DataItem, "Category"), DataBinder.Eval(Container.DataItem, "Post_ID")) %>'

Upvotes: 0

abatishchev
abatishchev

Reputation: 100278

Do you do

SELECT [Category] +  '.aspx?ID=' + [Post_ID]
FROM table

?

Try

SELECT CAST([Category] AS NVARCHAR(MAX)) + '.aspx?ID=' CAST([Post_ID] AS NVARCHAR(MAX))
FROM table

or specify max size depending on your columns' data type.


Above answer is bad. DON'T FORMAT ON DATA LAYER. FORMAT ON PRESENTATION LAYER, i.e. in mark-up. E.g.:

<asp:HyperLinkField
    HeaderText="LinkHeader"
    DataNavigateUrlFormatString="{0}.aspx?ID={1}" 
    DataNavigateUrlFields="Category,Post_ID"
    DataTextField="LinkName" />

(to work properly this requires also a field LinkName to exists in the resulting selection)

or

<asp:Hyperlink runat= "server"
    Text='<%# DataBinder.Eval(Container.DataItem, "LinkName").ToString() %>' 
    NavigateUrl='<%# DataBinder.Eval(Container.DataItem, "Category").ToString() + ".aspx?ID=" + DataBinder.Eval(Container.DataItem, "Post_ID").ToString() />   

Upvotes: 3

Martin Smith
Martin Smith

Reputation: 453287

I guess you're probably missing a cast. I agree that this seems an unlikely candidate for a computed column though.

create table #t
(
Category varchar(50),
[Post_ID] int
)

alter table #t 
add comp as ([Category] +  '.aspx?ID=' + cast([Post_ID] as varchar(10)))

Upvotes: 1

Related Questions